Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP vs JavaScript

Tags:

javascript

I have a background in OOP. I started to work a lot with JavaScript. As the project grows it's becoming more difficult to maintain it. In Java I apply OOP principles to keep things under control. What should I do with JavaScript, what should I study that is aimed at keeping a JavaScript application under control?

like image 772
SBel Avatar asked Mar 21 '12 20:03

SBel


People also ask

Is JavaScript good for OOP?

JavaScript leverages its prototype nature to welcome OOP developers to its ecosystem. It also provides easy ways to creating prototypes and organize related data. True OOP languages do not perform prototyping in the background - just take note of that.

Is JavaScript a OOP language?

JavaScript can function as both a procedural and an object oriented language.

Is JavaScript object-oriented or functional?

Thanks to new developments in ES6, we can say that JavaScript is both a functional as well as object-oriented programming language because of the various first-class features it provides.


2 Answers

You can apply OOP principles to Javascript development too. Javascript uses prototypal inheritance, but that is an implementation detail. The concepts are still the same. Most of the concepts with which you are familiar have direct analogues in javascript.

Other tried and true methods apply as well:

1) Stay DRY -- Do not Repeat Yourself. Duplicate code is always evil.
2) Separate concerns -- Use the MVC or MVVM patterns to keep code clean and doing only 1 thing.
3) Test -- When I hear "Difficult to maintain" my brain translates that into lack of tests. You can certainly write unit tests for javascript projects.
4) Code Review -- Code reviews can be a good way of rejecting duplicated code, code that is not crafted properly, not formatted, etc....

like image 89
hvgotcodes Avatar answered Sep 30 '22 13:09

hvgotcodes


This is how you define objects and methods in javascript.

function SomeObj() {

    this.someMethod = function() {
        alert('boo');
    }
}

var o_obj = new SomeObj();
o_obj.someMethod(); //alerts "boo"

Hope it helps.

You can also use prototype to create static functions.

this.prototype.someMethod = function() {
    alert('boo');
}
like image 23
C0D3 Avatar answered Sep 30 '22 13:09

C0D3