I'm sick of seeing dozens of different ways of doing object oriented programming in Javascript. Can anyone just tell me which technique I should use considering I want to work on a large scale project and I want my code to be future proof?
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.
These include: design patterns, abstraction, encapsulation, modularity, polymorphism, and inheritance. When not to use OOP: Putting square pegs in round holes: Don't wrap everything in classes when they don't need to be. Sometimes there is no need and the extra overhead just makes your code slower and more complex.
The object-oriented-programming antipattern is the excessive / unnecessary use of object-oriented-programming (OOP) and OOP techniques when simple procedural functions would have sufficed, with less overhead, fewer files to navigate around, fewer indirections to follow while debugging, etc.
Object-oriented programming aims to implement real-world entities like inheritance, abstraction, polymorphism, and encapsulation in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
These are just a few quick guidelines I've come up with, if anyone else has anything meaningful to add, I've set this answer as a community wiki so it should be easy enough for you to edit.
window['Andrew']['JS'] = { addEvent: function(el,evName) {/*Stuff*/}, Rectangle: function(width,height) {/*Stuff*/} };So then you would create a rectangle object by using:
var myRect = new Andrew.JS.Rectangle(14,11);And then your code will never interfere with, or be interfered by anybody else's
Rectangle
.var myRect = new Andrew.JS.Rectangle(14,11); document.write(myRect.getArea());
inSquareFeet()
.
myRect.getAreaObject().inSquareFeet();Make sure inSquareFeet is a method of the object returned by
getAreaObject()
and not a method of Andrew.JS.Rectangle
var Person = function() { this.name = ""; this.sayHello = function () { alert(this.name + " says 'Hello!'"); return this; } } var bob = new Person(); bob.name = "Bob Poulton"; bob.sayHello();try:
var Person = function(name) { this.name = name; this.sayHello = function () { alert(this.name + " says 'Hello!'"); return this; } } var bob = new Person("Bob Poulton"); bob.sayHello();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With