Object oriented programming in javascript

Is object oriented programming in javascript used? :slight_smile:

Yes but only by those who don’t realise that prototyping is far more powerful.

If you use object oriented processing in JavaScript you are only using a small fraction of what the language is capable of.

Prototyping isn’t object oriented? :stuck_out_tongue:

Object oriented programming is just a technique, the same way that procedural programming is. You can write procedural or OO code in JS, just as you can with PHP, Python or Ruby.

One important way that JS differs from those other languages is that it uses prototypal inheritance rather than classical (i.e. class-based) inheritance. As felgall alluded to, prototypal inheritance is more powerful than classical inheritance, although it is possible to [URL=“http://www.crockford.com/javascript/inheritance.html”]emulate classic inheritance in JS.

No it isn’t. Prototyping has approximately the same relationship to object oriented that object oriented has to procedural. Just as object oriented is far more powerful in many ways than procedural, prototyping is far more poweful than object oriented.

While you can write procedural or object oriented code in JavaScript, if you limit yourself to using those then you are missing out on the really powerful parts of javaScript.

OK. Well, actually, JavaScript is indeed object oriented, and “prototyping” is an object oriented design pattern. Where JS differs from languages like Java or C++ is in how they create new objects (based on a class blueprint vs based on a prototypical instance) and how they implement inheritance (classes inheriting from other classes vs objects inheriting from other objects via the “prototype chain”). But all of these behaviors nonetheless fall under the object oriented umbrella (software using a collection of interacting objects, where an object is a data structure with state and behavior bundled together).

Perhaps you’d like to clarify with code examples how you distinguish writing “prototyping” code vs writing object oriented code.

Well it depends… If you like OOP then you have to use it.

There’s little consensus about what OOP means when comparing programming languages. It’s the same thing with browser sniffing. The browser is IE but it sends out a FF user agent string. :slight_smile: Perhaps being more specific about the features you’re after would help spawn more productive answers.

Anyway, to the best of my knowledge, JS is best called “object based”. This is to say that JS doesn’t have specific mechanisms for classes which are found in a form or another in other languages. But this doesn’t mean that JS can’t emulate those patterns or even came up with some patterns of its own. Also, because JS is so flexible, a lot of patterns emerged and are still emerging.

Some patterns try to emulate OOP from Java or Ruby, for example. Others give different interpretation for the prototypal pattern in JS. In the end, for every feature like encapsulation, inheritance, there are a number of patterns. All you need to do is to make an educated choice given a specific problem.

@felgall ;

Isn’t it prototyping is just part of OOP?
Because as far as I know prototyping is just like extending the class?
Please correct me if I’m wrong.

Also can you give a sample demonstration codes showing it’s POWER ?

Thanks in advance felgall.

Prototyping in JavaScript is a a reference chain, a reference tree. It’s an easy way to get objects to share properties. This saves memory.

The problem is that if the reference tree grows too deep, then there are performance penalties.

So, the new wave JavaScript is “favor composition over inheritance”. This keeps the reference tree shallow, permits objects to share properties, which save memory and doesn’t have a negative impact on performance.

The simple rule is if the prototype chain is more than two-three levels deep, use composition instead, even if it means loosing the prototype mechanism on the way.

I’ve wondered myself what we should consider the prototype chain limit to be. I’ve never actually bothered to measure the performance differences before. So I googled around and found that someone has already set up a jsperf test.

Most browsers seem to have comparable speeds, except for the latest Chrome, which blows them all out of the water.

The latest Firefox and IE10 show similar patterns. Calling a function directly is moderately faster (10-15% or so), but calling a function through any of 1, 2, 3, or 4 prototype levels seems to take roughly the same amount of time.

Chrome’s results are downright weird. Calling a function from any prototype level was actually faster than calling the function directly. :shifty:

Most browsers, and especially Chrome, are slipping in so many and various kinds of optimizations that it’s getting harder to look at a line of code and be able to predict how it’ll perform. :-\

EDIT: This other jsperf test, on the other hand, has an almost identical setup, yet produces very different results.

EDIT EDIT: Actually, that second test has a bug in it. z.prototype = new z should have been z.prototype = new y. After I made that change, then the results started looking more like the first jsperf test.

JavaScript clearly has the basic features of object oriented programming.
You can create objects that encapsulate data and objects can have methods that can manipulate object’s data.
Objects can inherit properties and methods from other objects through prototype link.
You can use instanceof operator to check in objects is instance or a known type.

It does not have many of the more advanced features found in pure object oriented languages like Java for example.
It does not have reflection, it does not have support for annotations, does not have support for declaring type of variable and to require types for parameters, which is a very important part of most object oriented languages, even in php there is support for ‘type hinting’ which helps writing more resilient programs.
Until recently there was no way to make properties private (yes through closure tricks it was always possible), but not there is Object.defineProperty() which is a very ugly way to declare properties of other objects but at least you can make a read-only property now.
But originally JavaScript was designed to be run in the browser and to support just basic manipulation of html, even before the DOM model was finalized. It was also designed to be easy to learn, the idea was that a non-programmer can quickly learn to do basic things with JavaScript.

Now that JavaScript is popular server-side language it certanly shows all the limitations that I mentioned, but nevertheless it still works pretty well in node.js and because of original goal to be very easy to learn, it looks like Node.js popularity is growing very fast.

Since in JavaScript functions define scope, then depending on the inheritance pattern, actually there are more ways to make private members: in the constructor function or with IIFE (closures).

And if you’re talking about access modifiers, then read-only (writable: false) is not the equivalent for private, enumerable: false is.

Possible isn’t the same as intuitive. You can create private members of a JS class, but its not intuitive. Far from.

Javascript is object oriented. It consists of Objects, supports Encapsulation, allows for Polymorphism. These are the basic properties of an object oriented language. Unlike the unrelated Java language, or C++, Javascript uses prototypical inheritance as has already been pointed out up thread. Why? Because you can do that in a purely interpreted language. Since both Java and C++ require compilation, they cannot ever follow prototypical inheritance patterns because those patterns require the language to be able to apply Just In Time compiling.

While this leads to a very flexible and powerful language (albeit a bit sparse, though newer versions of the EMCA script standard do support “protected” and similar keywords) it does mean it will never be able to outperform it’s compiled cousins.

While we are on the subject, PHP occupies a weird worst-of-both-worlds middle ground. While it’s interpreted, that interpretation is by file rather than by line as with Javascript. As a result, PHP has all the limits of a compiled language with all of the limits of an interpreted one, and none of the advantages of either unless byte code caching is employed.

Are there any other languages that have prototypal inheritance? I mean other than JavaScript?

That’s the thing: you don’t have classes in JavaScript. Newer ECMAScript try to change that, but only as syntactic sugar. Sure, you can emulate classes, but the ones that emulate classes in JavaScript are the ones coming from Java or C++, that can’t wrap their heads around prototype-based programming.

There is no out-of-the-box support for encapsulation as in “restricted access to object’s member”, but it does support encapsulation as in “an object has method properties too”. Newer ECMAScript try to change that.

I wouldn’t say this is true. JavaScript is classless, even with newer syntactic sugar. It doesn’t use class constructors to instantiate new objects, it uses object cloning to build new objects that inherit from other objects. JavaScript inheritance is by delegation (prototype). JavaScript inheritance is by concatenation.

I’m not sure how you fit JIT into all this. I’m pretty sure you can delegate or concatenate in Java or C++ for prototype patterns. I’m pretty sure you can copy or clone instances in Java and C++.

Also, C++ doesn’t JIT. In fact, Java used JIT trying to prove it outperforms C++, which is pretty lame. C++ compiles to native. This means a platform specific optimization as close to the metal as possible. JIT produces a bytecode, which is a platform-free general optimization.

Yes, and this is true for Perl, Python, Ruby etcetera. What’s the point?

Yes. Lua, Object LISP. Also, using extensions, Perl, TCL, Python.

Everything you said is great. I want to add just one little nuance, mostly because I’ve heard this terminology occasionally used elsewhere as well. I don’t think “clone” is the right word to describe how JavaScript creates objects. Whether we’re speaking in casual conversation or programming jargon, the word “clone” means an exact and independent copy. The “independent” part is important, because we don’t get that feature from the way JavaScript creates objects. The new object will still be affected by changes to the original.

var original = {
    name: 'foo'
};

var isThisAClone = Object.create(original);

// it's an exact copy
console.log(isThisAClone.name); // foo

// but...
original.name = 'bar';

// it's not independent of the original
console.log(isThisAClone.name); // bar

I believe it is.

The nuance is more detailed inside the cloning mechanism, the inheritance method.

You want to shallow copy object methods (delegation) and you want to deep copy object state. Though there are cases where you want to deep copy everything and decouple objects completely.

It’s the terminology used in many libraries, with the nuances I mentioned above:

If you want a better word for it, then extend is another one used in many libraries, though it has slightly different functionality:

What I believe to be a point of confusion is how objects are always passed by reference in JavaScript. So, copy or clone, the result is the same when it comes to complex types. You need to specify deep to make things clear.

And yet, Object.create doesn’t do any copying of any kind – neither shallow nor deep. That’s why changing even just primitive values of the original affects the “clone”.

But none of those clone implementations use Object.create or the prototype chain to produce the result. Probably because that wouldn’t give us the behavior that we would expect of a clone.

Not a point of confusion. Not even primitive values are copied. That’s why changing a primitive value of the original still affects the clone.

Probably the least ambiguous is to say that x inherits from y, because JavaScript does inheritance only one way, and we know what behaviors that implies. It probably shouldn’t be ambiguous to say that x extends y or that we extended y to produce x, but alas some libraries implement extend as a “mix in”.

True. You have prototypes. And everything in javascript is an object. Even the functions are objects.

"class"ical inheritance
"prototyp"ical inheritance

They are two different things. Javascript doesn’t have classes because it doesn’t need them. You can emulate classes in the prototypical paradigm if you want to because it is much, much more powerful.

Newer ECMAScript try to change that, but only as syntactic sugar. Sure, you can emulate classes, but the ones that emulate classes in JavaScript are the ones coming from Java or C++, that can’t wrap their heads around prototype-based programming.

Or the ones that feel the language needs that functionality. I know I once did. Now, I’m not so sure if it needs it.

There is no out-of-the-box support for encapsulation as in “restricted access to object’s member”, but it does support encapsulation as in “an object has method properties too”. Newer ECMAScript try to change that.

Actually, there is - but it isn’t intuitive. It involves exploiting how scope works in js.

I’m not sure how you fit JIT into all this. I’m pretty sure you can delegate or concatenate in Java or C++ for prototype patterns. I’m pretty sure you can copy or clone instances in Java and C++.

There are no prototype patterns possible in Java or C++ because these languages cannot (well, probably more accurate to say should not - buffer overflowing is a key exploit concept) arbitrarily execute data as code.

Javascript allows you to compose wholly new blocks of executable code on the fly. This just isn’t possible in Java, C, or any other compiled language, precisely because they are compiled languages.

Also, C++ doesn’t JIT. In fact, Java used JIT trying to prove it outperforms C++, which is pretty lame. C++ compiles to native. This means a platform specific optimization as close to the metal as possible. JIT produces a bytecode, which is a platform-free general optimization.

Java doesn’t JIT code in the manner that a JS interpreter does. The bytecode of compiled Java runs on a specialized java virtual machine. You can run C code for a 68000 processor on an x86 machine with a virtual machine - hell you can run assembler for older processors on a virtual machine if you want. This is how MAME, BZSNES and the myriad other emulators out there work.

But Java doesn’t allow you to recompile the byte code at run time in any meaningful way. JavaScript does. JavaScript pays the price for this trick though - it’s hella slower than Java or C.