Learning .prototype - javascript

Edit: for those people seeing this post in the future, this site was undoubtedly critical for me to digest Javascript. If you're coming from a traditional OOP background, I HIGHLY recommend it. The UML-esq diagrams were amazing.
I still can't get my head around what the .prototype property in Javascript is. Is it simply a reference to another object? Or is it a reference to a pointer to another object? I come from C/C++/x86 and just can't see how it works. Let's look at some examples of how I currently see things; it'd help to point out my errors to see how things work. I don't even know if some of these are valid syntax. Object and Function are the global object/function objects respectively.
1 // Global.prototype = ??
2 // Function.prototype = ??
3
4 var obj1 = {}; // obj1.prototype = Object
5 obj2 = {}; // obj2.prototype = Object
6
7 var func1 = function() {}; // func1.prototype = Function
8 func2 = function() {}; // func2.prototype = Function
9 function func3() {} // func3.prototype = Function
10
I'm so confused.
11 var Foo = function() { this.prop1 = 0; }
12 var foo = new Foo(); // should it be 'new Foo' or 'new Foo()'?
13 // Foo.prototype = Function
14 // foo.prototype = Foo
15 var Goo = function() { this.prop2 = 0; }
16 var goo = new Goo();
17 // goo.prototype = Goo
18 goo.prototype = new Foo();
19 // goo.prop1 now exists ?
I also don't understand swapping prototypes around.
20 function A () {
21 this.prop1 = 1;
22 }
23 function B () {
24 this.prop2 = 2;
25 }
26 function C () {
27 this.prop3 = 3;
28 }
29 C.prototype = new B();
30 var c = new C();
31 // c.prop1 = 1
32 // c.prop2 = 2
33 // c.prop3 = undefined
34 C.prototype = new A();
35 // c.prop2 = 2???
36 // c.prop3 = 3
I can't get a grasp on the concept. I don't quite understand. I don't get how cloned objects get their own local copies of data, but changes to the original object (the prototype) somehow cascade down to the clones. I've been fiddling around with FigureBug trying things out, but mentally I can't come up with an idea that is consistent with every example ive seen
C++ may be a huge monstrosity, but at least I know exactly what's going. Here... I'm using my best guess..
Just a new paradigm I suppose. Anyways, thanks if you can help out... I'm turned upside-down on this .prototype.

Wow, that's a lot of questions. Let's work through them.
Is it simply a reference to another object? Or is it a reference to a pointer to another object?
There are no pointers in JavaScript. Yet, a variable or property holding "an object" is actually holding a reference to the object, so other variables can hold references to the same object.
Global.prototype = ??
The global object (window if you want), where all global variables are defined, has no prototype (don't care about exceptions in some environments).
I still can't get my head around what the .prototype property in Javascript is.
The .prototype property is a property that all function objects have, pointing to their prototype object (a plain object).
You must not confuse it with the internal prototype reference which each object has. That prototype points to the object where properties are looked up which an object doesn't have itself.
Function.prototype = ??
This is the object from which all Function objects inherit. It contains things like call or bind.
var obj1 = {}; // obj1.prototype = Object
var func1 = function() {}; // func1.prototype = Function
Yes, kinda. I think you've got the concept, but didn't know the terminology. While func.prototype is a different thing, the obj.prototype property doesn't even exist. However, you meant the internal prototypes - we can access them via the Object.getPrototypeOf function. And they don't refer to the constructor functions, but their prototype objects. Here's the correction:
Object.getPrototypeOf(obj1) === Object.prototype
Object.getPrototypeOf(func1) === Function.prototype
should it be 'new Foo' or 'new Foo()'?
That doesn't matter, they're equivalent. You only need the brackets explicitly when you want to pass arguments.
var Foo = function() { this.prop1 = 0; }
var foo = new Foo();
Again, your assumptions were correct but expressed wrong. Let's work through the details.
Above, I've talked about "prototype objects". What are those? They are plain objects which get implicitly created with every function. In this case, it's Foo.prototype - an empty object. So we deal here with three objects: The Foo constructor function, its Foo.prototype prototype object and the foo instance.
What's special about foo? It's the first thing which the new operator does. When a function is getting invoked as a constructor - with new - then its .prototype property is accessed and a new object is instantiated with its internal prototype set to that prototype object. That's the miraculous thing. After that the function is called on the new instance so that this is the new object; and in your case it creates the .prop1 property on the instance. Then the result is returned (and assigned to foo).
How to make use of that magic now? The point is to create properties on the prototype object, which will be inherited then.
// modify `Foo.prototype`, the object which `foo` inherits from:
Foo.prototype.prop2 = 1;
console.log(foo.prop2); // 1!
I also don't understand swapping prototypes around.
The problem is that this is quite impossible. Once instantiated, an object's prototype chain is quite static. However, you don't need that often.
goo.prototype = new Foo();
That didn't work because the .prototype property is not what you expected.
var c = new C();
C.prototype = new A();
That does work only a littlebit. Have a look above at what new does - it looks up the .prototype property of the constructor only once. The internal prototype stays locked then - you don't change the c instance. However, if you would create a new instance var d = new C() now then it would inherit from the A instance.
I hope this helps; if you have further questions please comment.

The prototype is used to search properties when the object itself doesn't have it defined, during reads. Writes always happen on the object itself
When you call
// An instance of Foo ({prop1:0}) is set as the
// prototype (to all instances of Goo)
var goo = new Goo();
// 0, from the prototype
console.log(goo.prop1);
// Read from the object itself (set in Goo's constructor)
console.log(goo.prop2);
// New instance, same prototype as goo
var goo2 = new Goo();
console.log(goo2.prop1) ; // 0, still from the prototype
// Setting is always at the object level, not the prototype
goo.prop1 = 5;
// goo2 is still reading from the prototype
console.log(goo2.prop1);
N.B.
Don't instantiate the parent class just to setup inheritance. See why here http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

Related

Is there any difference between ES6 class constructor functions and method? [duplicate]

What's the difference between
var A = function () {
this.x = function () {
//do something
};
};
and
var A = function () { };
A.prototype.x = function () {
//do something
};
The examples have very different outcomes.
Before looking at the differences, the following should be noted:
A constructor's prototype provides a way to share methods and values among instances via the instance's private [[Prototype]] property.
A function's this is set by how the function is called or by the use of bind (not discussed here). Where a function is called on an object (e.g. myObj.method()) then this within the method references the object. Where this is not set by the call or by the use of bind, it defaults to the global object (window in a browser) or in strict mode, remains undefined.
JavaScript is an object-oriented language, i.e. most values are objects, including functions. (Strings, numbers, and booleans are not objects.)
So here are the snippets in question:
var A = function () {
this.x = function () {
//do something
};
};
In this case, variable A is assigned a value that is a reference to a function. When that function is called using A(), the function's this isn't set by the call so it defaults to the global object and the expression this.x is effective window.x. The result is that a reference to the function expression on the right-hand side is assigned to window.x.
In the case of:
var A = function () { };
A.prototype.x = function () {
//do something
};
something very different occurs. In the first line, variable A is assigned a reference to a function. In JavaScript, all functions objects have a prototype property by default so there is no separate code to create an A.prototype object.
In the second line, A.prototype.x is assigned a reference to a function. This will create an x property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's x property is involved in the expression.
Another example is below. It's similar to the first one (and maybe what you meant to ask about):
var A = new function () {
this.x = function () {
//do something
};
};
In this example, the new operator has been added before the function expression so that the function is called as a constructor. When called with new, the function's this is set to reference a new Object whose private [[Prototype]] property is set to reference the constructor's public prototype. So in the assignment statement, the x property will be created on this new object. When called as a constructor, a function returns its this object by default, so there is no need for a separate return this; statement.
To check that A has an x property:
console.log(A.x) // function () {
// //do something
// };
This is an uncommon use of new since the only way to reference the constructor is via A.constructor. It would be much more common to do:
var A = function () {
this.x = function () {
//do something
};
};
var a = new A();
Another way of achieving a similar result is to use an immediately invoked function expression:
var A = (function () {
this.x = function () {
//do something
};
}());
In this case, A assigned the return value of calling the function on the right-hand side. Here again, since this is not set in the call, it will reference the global object and this.x is effective window.x. Since the function doesn't return anything, A will have a value of undefined.
These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:
var A = function () {
this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance));
// {"objectsOwnProperties":"are serialized"}
Related questions:
What does it mean that JavaScript is a prototypal language?
What is the scope of a function in JavaScript?
How does the "this" keyword work?
Sidenote: There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.
JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.
As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".
Here is some code to show this subtle difference:
// x is a method assigned to the object using "this"
var A = function () {
this.x = function () { alert('A'); };
};
A.prototype.updateX = function( value ) {
this.x = function() { alert( value ); }
};
var a1 = new A();
var a2 = new A();
a1.x(); // Displays 'A'
a2.x(); // Also displays 'A'
a1.updateX('Z');
a1.x(); // Displays 'Z'
a2.x(); // Still displays 'A'
// Here x is a method assigned to the object using "prototype"
var B = function () { };
B.prototype.x = function () { alert('B'); };
B.prototype.updateX = function( value ) {
B.prototype.x = function() { alert( value ); }
}
var b1 = new B();
var b2 = new B();
b1.x(); // Displays 'B'
b2.x(); // Also displays 'B'
b1.updateX('Y');
b1.x(); // Displays 'Y'
b2.x(); // Also displays 'Y' because by using prototype we have changed it for all instances
As others have mentioned, there are various reasons to choose one method or the other. My sample is just meant to clearly demonstrate the difference.
Take these 2 examples:
var A = function() { this.hey = function() { alert('from A') } };
vs.
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Most people here (especially the top-rated answers) tried to explain how they are different without explaining WHY. I think this is wrong and if you understand the fundamentals first, the difference will become obvious. Let's try to explain the fundamentals first...
a) A function is an object in JavaScript. EVERY object in JavaScript gets an internal property (meaning, you can't access it like other properties, except maybe in browsers like Chrome), often referred to as __proto__ (you can actually type anyObject.__proto__ in Chrome to see what it references. This is just that, a property, nothing more. A property in JavaScript = a variable inside an object, nothing more. What do variables do? They point to things.
So what does this __proto__ property points to? Well, usually another object (we'll explain why later). The only way to force JavaScript for the __proto__ property to NOT point to another object is to use var newObj = Object.create(null). Even if you do this, the __proto__ property STILL exists as a property of the object, just it doesn't point to another object, it points to null.
Here's where most people get confused:
When you create a new function in JavaScript (which is an object as well, remember?), the moment it is defined, JavaScript automatically creates a new property on that function called prototype. Try it:
var A = [];
A.prototype // undefined
A = function() {}
A.prototype // {} // got created when function() {} was defined
A.prototype is TOTALLY DIFFERENT from the __proto__ property. In our example, 'A' now has TWO properties called 'prototype' and __proto__ . This is a big confusion for people. prototype and __proto__ properties are in no way related, they're separate things pointing to separate values.
You may wonder: Why does JavaScript has __proto__ property created on every single object? Well, one word: delegation. When you call a property on an object and the object doesn't have it, then JavaScript looks for the object referenced by __proto__ to see if it maybe has it. If it doesn't have it, then it looks at that object's __proto__ property and so on...until the chain ends. Thus the name prototype chain. Of course, if __proto__ doesn't point to an object and instead points to null, well tough luck, JavaScript realizes that and will return you undefined for the property.
You may also wonder, why does JavaScript creates a property called prototype for a function when you define the function? Because it tries to fool you, yes fool you that it works like class-based languages.
Let's go on with our example and create an "object" out of A:
var a1 = new A();
There's something happening in the background when this thing happened. a1 is an ordinary variable which was assigned a new, empty object.
The fact that you used the operator new before a function invocation A() did something ADDITIONAL in the background. The new keyword created a new object which now references a1 and that object is empty. Here's what happening additionally:
We said that on each function definition there's a new property created called prototype (which you can access it, unlike with the __proto__ property) created? Well, that property is being used now.
So we're now at the point where we have a freshly baked empty a1 object. We said that all objects in JavaScript have an internal __proto__ property which points to something (a1 also has it), whether it's null or another object. What the new operator does is that it sets that __proto__ property to point to the function's prototype property. Read that again. It's basically this:
a1.__proto__ = A.prototype;
We said that A.prototype is nothing more than an empty object (unless we change it to something else before defining a1). So now basically a1.__proto__ points to the same thing A.prototype points to, which is that empty object. They both point to the same object which was created when this line happened:
A = function() {} // JS: cool. let's also create A.prototype pointing to empty {}
Now, there's another thing happening when var a1 = new A() statement is processed. Basically A() is executed and if A is something like this:
var A = function() { this.hey = function() { alert('from A') } };
All that stuff inside function() { } is going to execute. When you reach the this.hey.. line, this is changed to a1 and you get this:
a1.hey = function() { alert('from A') }
I won't cover why this changes to a1 but this is a great answer to learn more.
So to summarize, when you do var a1 = new A() there are 3 things happening in the background:
A totally new empty object is created and assigned to a1. a1 = {}
a1.__proto__ property is assigned to point at the same thing as A.prototype points to (another empty object {} )
The function A() is being executed with this set to the new, empty object created in step 1 (read the answer I referenced above as to why this changes to a1)
Now, let's try to create another object:
var a2 = new A();
Steps 1,2,3 will repeat. Do you notice something? The key word is repeat. Step 1: a2 will be a new empty object, step 2: its __proto__ property will point to the same thing A.prototype points to and most importantly, step 3: function A() is AGAIN executed, which means that a2 will get hey property containing a function. a1 and a2 have two SEPARATE properties named hey which point to 2 SEPARATE functions! We now have duplicate functions in same two different objects doing the same thing, oops...You can imagine the memory implications of this if we have 1000 objects created with new A, after all functions declarations take more memory than something like the number 2. So how do we prevent this?
Remember why the __proto__ property exists on every object? So that if you retrieve the yoMan property on a1 (which doesn't exist), its __proto__ property will be consulted, which if it's an object (and is most cases it is), it will check if it contains yoMan, and if it doesn't, it will consult that object's __proto__ etc. If it does, it will take that property value and display it to you.
So someone decided to use this fact + the fact that when you create a1, its __proto__ property points to the same (empty) object A.prototype points to and do this:
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Cool! Now, when you create a1, it again goes through all of the 3 steps above, and in step 3, it doesn't do anything, since function A() has nothing to execute. And if we do:
a1.hey
It will see that a1 does not contain hey and it will check its __proto__ property object to see if it has it, which is the case.
With this approach we eliminate the part from step 3 where functions are duplicated on each new object creation. Instead of a1 and a2 having a separate hey property, now NONE of them has it. Which, I guess, you figured out yourself by now. That's the nice thing...if you understand __proto__ and Function.prototype, questions like these will be pretty obvious.
NOTE: Some people tend to not call the internal Prototype property as __proto__, I've used this name through the post to distinguish it clearly to the Functional.prototype property as two different things.
In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.
A reason to use the first form is to access "private members". For example:
var A = function () {
var private_var = ...;
this.x = function () {
return private_var;
};
this.setX = function (new_x) {
private_var = new_x;
};
};
Because of javascript's scoping rules, private_var is available to the function assigned to this.x, but not outside the object.
The first example changes the interface for that object only. The second example changes the interface for all object of that class.
The ultimate problem with using this instead of prototype is that when overriding a method, the constructor of the base class will still refer to the overridden method. Consider this:
BaseClass = function() {
var text = null;
this.setText = function(value) {
text = value + " BaseClass!";
};
this.getText = function() {
return text;
};
this.setText("Hello"); // This always calls BaseClass.setText()
};
SubClass = function() {
// setText is not overridden yet,
// so the constructor calls the superclass' method
BaseClass.call(this);
// Keeping a reference to the superclass' method
var super_setText = this.setText;
// Overriding
this.setText = function(value) {
super_setText.call(this, "SubClass says: " + value);
};
};
SubClass.prototype = new BaseClass();
var subClass = new SubClass();
console.log(subClass.getText()); // Hello BaseClass!
subClass.setText("Hello"); // setText is already overridden
console.log(subClass.getText()); // SubClass says: Hello BaseClass!
versus:
BaseClass = function() {
this.setText("Hello"); // This calls the overridden method
};
BaseClass.prototype.setText = function(value) {
this.text = value + " BaseClass!";
};
BaseClass.prototype.getText = function() {
return this.text;
};
SubClass = function() {
// setText is already overridden, so this works as expected
BaseClass.call(this);
};
SubClass.prototype = new BaseClass();
SubClass.prototype.setText = function(value) {
BaseClass.prototype.setText.call(this, "SubClass says: " + value);
};
var subClass = new SubClass();
console.log(subClass.getText()); // SubClass says: Hello BaseClass!
If you think this is not a problem, then it depends on whether you can live without private variables, and whether you are experienced enough to know a leak when you see one. Also, having to put the constructor logic after the method definitions is inconvenient.
var A = function (param1) {
var privateVar = null; // Private variable
// Calling this.setPrivateVar(param1) here would be an error
this.setPrivateVar = function (value) {
privateVar = value;
console.log("setPrivateVar value set to: " + value);
// param1 is still here, possible memory leak
console.log("setPrivateVar has param1: " + param1);
};
// The constructor logic starts here possibly after
// many lines of code that define methods
this.setPrivateVar(param1); // This is valid
};
var a = new A(0);
// setPrivateVar value set to: 0
// setPrivateVar has param1: 0
a.setPrivateVar(1);
//setPrivateVar value set to: 1
//setPrivateVar has param1: 0
versus:
var A = function (param1) {
this.setPublicVar(param1); // This is valid
};
A.prototype.setPublicVar = function (value) {
this.publicVar = value; // No private variable
};
var a = new A(0);
a.setPublicVar(1);
console.log(a.publicVar); // 1
Every object is linked to a prototype object. When trying to access a property that does not exist, JavaScript will look in the object's prototype object for that property and return it if it exists.
The prototype property of a function constructor refers to the prototype object of all instances created with that function when using new.
In your first example, you are adding a property x to each instance created with the A function.
var A = function () {
this.x = function () {
//do something
};
};
var a = new A(); // constructor function gets executed
// newly created object gets an 'x' property
// which is a function
a.x(); // and can be called like this
In the second example you are adding a property to the prototype object that all the instances created with A point to.
var A = function () { };
A.prototype.x = function () {
//do something
};
var a = new A(); // constructor function gets executed
// which does nothing in this example
a.x(); // you are trying to access the 'x' property of an instance of 'A'
// which does not exist
// so JavaScript looks for that property in the prototype object
// that was defined using the 'prototype' property of the constructor
In conclusion, in the first example a copy of the function is assigned to each instance. In the second example a single copy of the function is shared by all instances.
What's the difference? => A lot.
I think, the this version is used to enable encapsulation, i.e. data hiding.
It helps to manipulate private variables.
Let us look at the following example:
var AdultPerson = function() {
var age;
this.setAge = function(val) {
// some housekeeping
age = val >= 18 && val;
};
this.getAge = function() {
return age;
};
this.isValid = function() {
return !!age;
};
};
Now, the prototype structure can be applied as following:
Different adults have different ages, but all of the adults get the same rights.
So, we add it using prototype, rather than this.
AdultPerson.prototype.getRights = function() {
// Should be valid
return this.isValid() && ['Booze', 'Drive'];
};
Lets look at the implementation now.
var p1 = new AdultPerson;
p1.setAge(12); // ( age = false )
console.log(p1.getRights()); // false ( Kid alert! )
p1.setAge(19); // ( age = 19 )
console.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )
var p2 = new AdultPerson;
p2.setAge(45);
console.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***
Hope this helps.
I know this has been answered to death but I'd like to show an actual example of speed differences.
Function directly on object:
function ExampleFn() {
this.print = function() {
console.log("Calling print! ");
}
}
var objects = [];
console.time('x');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('x');
//x: 1151.960693359375ms
Function on prototype:
function ExampleFn() {
}
ExampleFn.prototype.print = function() {
console.log("Calling print!");
}
var objects = [];
console.time('y');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('y');
//x: 617.866943359375ms
Here we're creating 2,000,000 new objects with a print method in Chrome. We're storing every object in an array. Putting print on the prototype takes about 1/2 as long.
Prototype is the template of the class; which applies to all future instances of it. Whereas this is the particular instance of the object.
Let me give you a more comprehensive answer that I learned during a JavaScript training course.
Most answers mentioned the difference already, i.e. when prototyping the function is shared with all (future) instances. Whereas declaring the function in the class will create a copy for each instance.
In general there is no right or wrong, it's more a matter of taste or a design decision depending on your requirements. The prototype however is the technique that is used to develop in an object oriented manner, as I hope you'll see at the end of this answer.
You showed two patterns in your question. I will try to explain two more and try to explain the differences if relevant. Feel free to edit/extend.
In all examples it is about a car object that has a location and can move.
Object Decorator pattern
Not sure if this pattern is still relevant nowadays, but it exists. And it is good to know about it.
You simply pass an object and a property to the decorator function. The decorator returns the object with property and method.
var carlike = function(obj, loc) {
obj.loc = loc;
obj.move = function() {
obj.loc++;
};
return obj;
};
var amy = carlike({}, 1);
amy.move();
var ben = carlike({}, 9);
ben.move();
Functional Classes
A function in JavaScript is a specialised object. In addition to being invoked, a function can store properties like any other object.
In this case Car is a function (also think object) that can be invoked as you are used to do. It has a property methods (which is an object with a move function). When Car is invoked the extend function is called, which does some magic, and extends the Car function (think object) with the methods defined within methods.
This example, though different, comes closest to the first example in the question.
var Car = function(loc) {
var obj = {loc: loc};
extend(obj, Car.methods);
return obj;
};
Car.methods = {
move : function() {
this.loc++;
}
};
var amy = Car(1);
amy.move();
var ben = Car(9);
ben.move();
Prototypal Classes
The first two patterns allow a discussion of using techniques to define shared methods or using methods that are defined inline in the body of the constructor. In both cases every instance has its own move function.
The prototypal pattern does not lend itself well to the same examination, because function sharing via a prototype delegation is the very goal for the prototypal pattern. As others pointed out, it is expected to have a better memory footprint.
However there is one point interesting to know:
Every prototype object has has a convenience property constructor, which points back to the function (think object) it came attached to.
Concerning the last three lines:
In this example Car links to the prototype object, which links via constructor to Car itself, i.e. Car.prototype.constructor is Car itself. This allows you to figure out which constructor function built a certain object.
amy.constructor's lookup fails and thus is delegated to Car.prototype, which does have the constructor property. And so amy.constructor is Car.
Furthermore, amy is an instanceof Car. The instanceof operator works by seeing if the right operand's prototype object (Car) can be found anywhere in the left operand's prototype (amy) chain.
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
return obj;
};
Car.prototype.move = function() {
this.loc++;
};
var amy = Car(1);
amy.move();
var ben = Car(9);
ben.move();
console.log(Car.prototype.constructor);
console.log(amy.constructor);
console.log(amy instanceof Car);
Some developers can be confused in the beginning. See below example:
var Dog = function() {
return {legs: 4, bark: alert};
};
var fido = Dog();
console.log(fido instanceof Dog);
The instanceof operator returns false, because Dog's prototype cannot be found anywhere in fido's prototype chain. fido is a simple object that is created with an object literal, i.e. it just delegates to Object.prototype.
Pseudoclassical patterns
This is really just another form of the prototypal pattern in simplified form and more familiar to do those who program in Java for example, since it uses the new constructor.
It does the same as in the prototypal pattern really, it is just syntactic sugar overtop of the prototypal pattern.
However, the primary difference is that there are optimizations implemented in JavaScript engines that only apply when using the pseudoclassical pattern. Think of the pseudoclassical pattern a probably faster version of the prototypal pattern; the object relations in both examples are the same.
var Car = function(loc) {
this.loc = loc;
};
Car.prototype.move = function() {
this.loc++;
};
var amy = new Car(1);
amy.move();
var ben = new Car(9);
ben.move();
Finally, it should not be too difficult to realize how object oriented programming can be done. There are two sections.
One section that defines common properties/methods in the prototype (chain).
And another section where you put the definitions that distinguish the objects from each other (loc variable in the examples).
This is what allows us to apply concepts like superclass or subclass in JavaScript.
Feel free to add or edit. Once more complete I could make this a community wiki maybe.
I believe that #Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.
var A = function() {};
A.prototype = {
_instance_var: 0,
initialize: function(v) { this._instance_var = v; },
x: function() { alert(this._instance_var); }
};
EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.
As discussed in other answers, it's really a performance consideration because the function in the prototype is shared with all of the instantiations - rather than the function being created for each instantiation.
I put together a jsperf to show this. There is a dramatic difference in the time it takes to instantiate the class, although it is really only relevant if you are making many instances.
http://jsperf.com/functions-in-constructor-vs-prototype
Think about statically typed language, things on prototype are static and things on this are instance related.
When you use prototype, the function will only be loaded only once into memory (independently on the amount of objects you create) and you can override the function whenever you want.

Understanding 'this' and 'prototype' in JavaScript ? [duplicate]

What's the difference between
var A = function () {
this.x = function () {
//do something
};
};
and
var A = function () { };
A.prototype.x = function () {
//do something
};
The examples have very different outcomes.
Before looking at the differences, the following should be noted:
A constructor's prototype provides a way to share methods and values among instances via the instance's private [[Prototype]] property.
A function's this is set by how the function is called or by the use of bind (not discussed here). Where a function is called on an object (e.g. myObj.method()) then this within the method references the object. Where this is not set by the call or by the use of bind, it defaults to the global object (window in a browser) or in strict mode, remains undefined.
JavaScript is an object-oriented language, i.e. most values are objects, including functions. (Strings, numbers, and booleans are not objects.)
So here are the snippets in question:
var A = function () {
this.x = function () {
//do something
};
};
In this case, variable A is assigned a value that is a reference to a function. When that function is called using A(), the function's this isn't set by the call so it defaults to the global object and the expression this.x is effective window.x. The result is that a reference to the function expression on the right-hand side is assigned to window.x.
In the case of:
var A = function () { };
A.prototype.x = function () {
//do something
};
something very different occurs. In the first line, variable A is assigned a reference to a function. In JavaScript, all functions objects have a prototype property by default so there is no separate code to create an A.prototype object.
In the second line, A.prototype.x is assigned a reference to a function. This will create an x property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's x property is involved in the expression.
Another example is below. It's similar to the first one (and maybe what you meant to ask about):
var A = new function () {
this.x = function () {
//do something
};
};
In this example, the new operator has been added before the function expression so that the function is called as a constructor. When called with new, the function's this is set to reference a new Object whose private [[Prototype]] property is set to reference the constructor's public prototype. So in the assignment statement, the x property will be created on this new object. When called as a constructor, a function returns its this object by default, so there is no need for a separate return this; statement.
To check that A has an x property:
console.log(A.x) // function () {
// //do something
// };
This is an uncommon use of new since the only way to reference the constructor is via A.constructor. It would be much more common to do:
var A = function () {
this.x = function () {
//do something
};
};
var a = new A();
Another way of achieving a similar result is to use an immediately invoked function expression:
var A = (function () {
this.x = function () {
//do something
};
}());
In this case, A assigned the return value of calling the function on the right-hand side. Here again, since this is not set in the call, it will reference the global object and this.x is effective window.x. Since the function doesn't return anything, A will have a value of undefined.
These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:
var A = function () {
this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance));
// {"objectsOwnProperties":"are serialized"}
Related questions:
What does it mean that JavaScript is a prototypal language?
What is the scope of a function in JavaScript?
How does the "this" keyword work?
Sidenote: There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.
JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.
As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".
Here is some code to show this subtle difference:
// x is a method assigned to the object using "this"
var A = function () {
this.x = function () { alert('A'); };
};
A.prototype.updateX = function( value ) {
this.x = function() { alert( value ); }
};
var a1 = new A();
var a2 = new A();
a1.x(); // Displays 'A'
a2.x(); // Also displays 'A'
a1.updateX('Z');
a1.x(); // Displays 'Z'
a2.x(); // Still displays 'A'
// Here x is a method assigned to the object using "prototype"
var B = function () { };
B.prototype.x = function () { alert('B'); };
B.prototype.updateX = function( value ) {
B.prototype.x = function() { alert( value ); }
}
var b1 = new B();
var b2 = new B();
b1.x(); // Displays 'B'
b2.x(); // Also displays 'B'
b1.updateX('Y');
b1.x(); // Displays 'Y'
b2.x(); // Also displays 'Y' because by using prototype we have changed it for all instances
As others have mentioned, there are various reasons to choose one method or the other. My sample is just meant to clearly demonstrate the difference.
Take these 2 examples:
var A = function() { this.hey = function() { alert('from A') } };
vs.
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Most people here (especially the top-rated answers) tried to explain how they are different without explaining WHY. I think this is wrong and if you understand the fundamentals first, the difference will become obvious. Let's try to explain the fundamentals first...
a) A function is an object in JavaScript. EVERY object in JavaScript gets an internal property (meaning, you can't access it like other properties, except maybe in browsers like Chrome), often referred to as __proto__ (you can actually type anyObject.__proto__ in Chrome to see what it references. This is just that, a property, nothing more. A property in JavaScript = a variable inside an object, nothing more. What do variables do? They point to things.
So what does this __proto__ property points to? Well, usually another object (we'll explain why later). The only way to force JavaScript for the __proto__ property to NOT point to another object is to use var newObj = Object.create(null). Even if you do this, the __proto__ property STILL exists as a property of the object, just it doesn't point to another object, it points to null.
Here's where most people get confused:
When you create a new function in JavaScript (which is an object as well, remember?), the moment it is defined, JavaScript automatically creates a new property on that function called prototype. Try it:
var A = [];
A.prototype // undefined
A = function() {}
A.prototype // {} // got created when function() {} was defined
A.prototype is TOTALLY DIFFERENT from the __proto__ property. In our example, 'A' now has TWO properties called 'prototype' and __proto__ . This is a big confusion for people. prototype and __proto__ properties are in no way related, they're separate things pointing to separate values.
You may wonder: Why does JavaScript has __proto__ property created on every single object? Well, one word: delegation. When you call a property on an object and the object doesn't have it, then JavaScript looks for the object referenced by __proto__ to see if it maybe has it. If it doesn't have it, then it looks at that object's __proto__ property and so on...until the chain ends. Thus the name prototype chain. Of course, if __proto__ doesn't point to an object and instead points to null, well tough luck, JavaScript realizes that and will return you undefined for the property.
You may also wonder, why does JavaScript creates a property called prototype for a function when you define the function? Because it tries to fool you, yes fool you that it works like class-based languages.
Let's go on with our example and create an "object" out of A:
var a1 = new A();
There's something happening in the background when this thing happened. a1 is an ordinary variable which was assigned a new, empty object.
The fact that you used the operator new before a function invocation A() did something ADDITIONAL in the background. The new keyword created a new object which now references a1 and that object is empty. Here's what happening additionally:
We said that on each function definition there's a new property created called prototype (which you can access it, unlike with the __proto__ property) created? Well, that property is being used now.
So we're now at the point where we have a freshly baked empty a1 object. We said that all objects in JavaScript have an internal __proto__ property which points to something (a1 also has it), whether it's null or another object. What the new operator does is that it sets that __proto__ property to point to the function's prototype property. Read that again. It's basically this:
a1.__proto__ = A.prototype;
We said that A.prototype is nothing more than an empty object (unless we change it to something else before defining a1). So now basically a1.__proto__ points to the same thing A.prototype points to, which is that empty object. They both point to the same object which was created when this line happened:
A = function() {} // JS: cool. let's also create A.prototype pointing to empty {}
Now, there's another thing happening when var a1 = new A() statement is processed. Basically A() is executed and if A is something like this:
var A = function() { this.hey = function() { alert('from A') } };
All that stuff inside function() { } is going to execute. When you reach the this.hey.. line, this is changed to a1 and you get this:
a1.hey = function() { alert('from A') }
I won't cover why this changes to a1 but this is a great answer to learn more.
So to summarize, when you do var a1 = new A() there are 3 things happening in the background:
A totally new empty object is created and assigned to a1. a1 = {}
a1.__proto__ property is assigned to point at the same thing as A.prototype points to (another empty object {} )
The function A() is being executed with this set to the new, empty object created in step 1 (read the answer I referenced above as to why this changes to a1)
Now, let's try to create another object:
var a2 = new A();
Steps 1,2,3 will repeat. Do you notice something? The key word is repeat. Step 1: a2 will be a new empty object, step 2: its __proto__ property will point to the same thing A.prototype points to and most importantly, step 3: function A() is AGAIN executed, which means that a2 will get hey property containing a function. a1 and a2 have two SEPARATE properties named hey which point to 2 SEPARATE functions! We now have duplicate functions in same two different objects doing the same thing, oops...You can imagine the memory implications of this if we have 1000 objects created with new A, after all functions declarations take more memory than something like the number 2. So how do we prevent this?
Remember why the __proto__ property exists on every object? So that if you retrieve the yoMan property on a1 (which doesn't exist), its __proto__ property will be consulted, which if it's an object (and is most cases it is), it will check if it contains yoMan, and if it doesn't, it will consult that object's __proto__ etc. If it does, it will take that property value and display it to you.
So someone decided to use this fact + the fact that when you create a1, its __proto__ property points to the same (empty) object A.prototype points to and do this:
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Cool! Now, when you create a1, it again goes through all of the 3 steps above, and in step 3, it doesn't do anything, since function A() has nothing to execute. And if we do:
a1.hey
It will see that a1 does not contain hey and it will check its __proto__ property object to see if it has it, which is the case.
With this approach we eliminate the part from step 3 where functions are duplicated on each new object creation. Instead of a1 and a2 having a separate hey property, now NONE of them has it. Which, I guess, you figured out yourself by now. That's the nice thing...if you understand __proto__ and Function.prototype, questions like these will be pretty obvious.
NOTE: Some people tend to not call the internal Prototype property as __proto__, I've used this name through the post to distinguish it clearly to the Functional.prototype property as two different things.
In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.
A reason to use the first form is to access "private members". For example:
var A = function () {
var private_var = ...;
this.x = function () {
return private_var;
};
this.setX = function (new_x) {
private_var = new_x;
};
};
Because of javascript's scoping rules, private_var is available to the function assigned to this.x, but not outside the object.
The first example changes the interface for that object only. The second example changes the interface for all object of that class.
The ultimate problem with using this instead of prototype is that when overriding a method, the constructor of the base class will still refer to the overridden method. Consider this:
BaseClass = function() {
var text = null;
this.setText = function(value) {
text = value + " BaseClass!";
};
this.getText = function() {
return text;
};
this.setText("Hello"); // This always calls BaseClass.setText()
};
SubClass = function() {
// setText is not overridden yet,
// so the constructor calls the superclass' method
BaseClass.call(this);
// Keeping a reference to the superclass' method
var super_setText = this.setText;
// Overriding
this.setText = function(value) {
super_setText.call(this, "SubClass says: " + value);
};
};
SubClass.prototype = new BaseClass();
var subClass = new SubClass();
console.log(subClass.getText()); // Hello BaseClass!
subClass.setText("Hello"); // setText is already overridden
console.log(subClass.getText()); // SubClass says: Hello BaseClass!
versus:
BaseClass = function() {
this.setText("Hello"); // This calls the overridden method
};
BaseClass.prototype.setText = function(value) {
this.text = value + " BaseClass!";
};
BaseClass.prototype.getText = function() {
return this.text;
};
SubClass = function() {
// setText is already overridden, so this works as expected
BaseClass.call(this);
};
SubClass.prototype = new BaseClass();
SubClass.prototype.setText = function(value) {
BaseClass.prototype.setText.call(this, "SubClass says: " + value);
};
var subClass = new SubClass();
console.log(subClass.getText()); // SubClass says: Hello BaseClass!
If you think this is not a problem, then it depends on whether you can live without private variables, and whether you are experienced enough to know a leak when you see one. Also, having to put the constructor logic after the method definitions is inconvenient.
var A = function (param1) {
var privateVar = null; // Private variable
// Calling this.setPrivateVar(param1) here would be an error
this.setPrivateVar = function (value) {
privateVar = value;
console.log("setPrivateVar value set to: " + value);
// param1 is still here, possible memory leak
console.log("setPrivateVar has param1: " + param1);
};
// The constructor logic starts here possibly after
// many lines of code that define methods
this.setPrivateVar(param1); // This is valid
};
var a = new A(0);
// setPrivateVar value set to: 0
// setPrivateVar has param1: 0
a.setPrivateVar(1);
//setPrivateVar value set to: 1
//setPrivateVar has param1: 0
versus:
var A = function (param1) {
this.setPublicVar(param1); // This is valid
};
A.prototype.setPublicVar = function (value) {
this.publicVar = value; // No private variable
};
var a = new A(0);
a.setPublicVar(1);
console.log(a.publicVar); // 1
Every object is linked to a prototype object. When trying to access a property that does not exist, JavaScript will look in the object's prototype object for that property and return it if it exists.
The prototype property of a function constructor refers to the prototype object of all instances created with that function when using new.
In your first example, you are adding a property x to each instance created with the A function.
var A = function () {
this.x = function () {
//do something
};
};
var a = new A(); // constructor function gets executed
// newly created object gets an 'x' property
// which is a function
a.x(); // and can be called like this
In the second example you are adding a property to the prototype object that all the instances created with A point to.
var A = function () { };
A.prototype.x = function () {
//do something
};
var a = new A(); // constructor function gets executed
// which does nothing in this example
a.x(); // you are trying to access the 'x' property of an instance of 'A'
// which does not exist
// so JavaScript looks for that property in the prototype object
// that was defined using the 'prototype' property of the constructor
In conclusion, in the first example a copy of the function is assigned to each instance. In the second example a single copy of the function is shared by all instances.
What's the difference? => A lot.
I think, the this version is used to enable encapsulation, i.e. data hiding.
It helps to manipulate private variables.
Let us look at the following example:
var AdultPerson = function() {
var age;
this.setAge = function(val) {
// some housekeeping
age = val >= 18 && val;
};
this.getAge = function() {
return age;
};
this.isValid = function() {
return !!age;
};
};
Now, the prototype structure can be applied as following:
Different adults have different ages, but all of the adults get the same rights.
So, we add it using prototype, rather than this.
AdultPerson.prototype.getRights = function() {
// Should be valid
return this.isValid() && ['Booze', 'Drive'];
};
Lets look at the implementation now.
var p1 = new AdultPerson;
p1.setAge(12); // ( age = false )
console.log(p1.getRights()); // false ( Kid alert! )
p1.setAge(19); // ( age = 19 )
console.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )
var p2 = new AdultPerson;
p2.setAge(45);
console.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***
Hope this helps.
I know this has been answered to death but I'd like to show an actual example of speed differences.
Function directly on object:
function ExampleFn() {
this.print = function() {
console.log("Calling print! ");
}
}
var objects = [];
console.time('x');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('x');
//x: 1151.960693359375ms
Function on prototype:
function ExampleFn() {
}
ExampleFn.prototype.print = function() {
console.log("Calling print!");
}
var objects = [];
console.time('y');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('y');
//x: 617.866943359375ms
Here we're creating 2,000,000 new objects with a print method in Chrome. We're storing every object in an array. Putting print on the prototype takes about 1/2 as long.
Prototype is the template of the class; which applies to all future instances of it. Whereas this is the particular instance of the object.
Let me give you a more comprehensive answer that I learned during a JavaScript training course.
Most answers mentioned the difference already, i.e. when prototyping the function is shared with all (future) instances. Whereas declaring the function in the class will create a copy for each instance.
In general there is no right or wrong, it's more a matter of taste or a design decision depending on your requirements. The prototype however is the technique that is used to develop in an object oriented manner, as I hope you'll see at the end of this answer.
You showed two patterns in your question. I will try to explain two more and try to explain the differences if relevant. Feel free to edit/extend.
In all examples it is about a car object that has a location and can move.
Object Decorator pattern
Not sure if this pattern is still relevant nowadays, but it exists. And it is good to know about it.
You simply pass an object and a property to the decorator function. The decorator returns the object with property and method.
var carlike = function(obj, loc) {
obj.loc = loc;
obj.move = function() {
obj.loc++;
};
return obj;
};
var amy = carlike({}, 1);
amy.move();
var ben = carlike({}, 9);
ben.move();
Functional Classes
A function in JavaScript is a specialised object. In addition to being invoked, a function can store properties like any other object.
In this case Car is a function (also think object) that can be invoked as you are used to do. It has a property methods (which is an object with a move function). When Car is invoked the extend function is called, which does some magic, and extends the Car function (think object) with the methods defined within methods.
This example, though different, comes closest to the first example in the question.
var Car = function(loc) {
var obj = {loc: loc};
extend(obj, Car.methods);
return obj;
};
Car.methods = {
move : function() {
this.loc++;
}
};
var amy = Car(1);
amy.move();
var ben = Car(9);
ben.move();
Prototypal Classes
The first two patterns allow a discussion of using techniques to define shared methods or using methods that are defined inline in the body of the constructor. In both cases every instance has its own move function.
The prototypal pattern does not lend itself well to the same examination, because function sharing via a prototype delegation is the very goal for the prototypal pattern. As others pointed out, it is expected to have a better memory footprint.
However there is one point interesting to know:
Every prototype object has has a convenience property constructor, which points back to the function (think object) it came attached to.
Concerning the last three lines:
In this example Car links to the prototype object, which links via constructor to Car itself, i.e. Car.prototype.constructor is Car itself. This allows you to figure out which constructor function built a certain object.
amy.constructor's lookup fails and thus is delegated to Car.prototype, which does have the constructor property. And so amy.constructor is Car.
Furthermore, amy is an instanceof Car. The instanceof operator works by seeing if the right operand's prototype object (Car) can be found anywhere in the left operand's prototype (amy) chain.
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
return obj;
};
Car.prototype.move = function() {
this.loc++;
};
var amy = Car(1);
amy.move();
var ben = Car(9);
ben.move();
console.log(Car.prototype.constructor);
console.log(amy.constructor);
console.log(amy instanceof Car);
Some developers can be confused in the beginning. See below example:
var Dog = function() {
return {legs: 4, bark: alert};
};
var fido = Dog();
console.log(fido instanceof Dog);
The instanceof operator returns false, because Dog's prototype cannot be found anywhere in fido's prototype chain. fido is a simple object that is created with an object literal, i.e. it just delegates to Object.prototype.
Pseudoclassical patterns
This is really just another form of the prototypal pattern in simplified form and more familiar to do those who program in Java for example, since it uses the new constructor.
It does the same as in the prototypal pattern really, it is just syntactic sugar overtop of the prototypal pattern.
However, the primary difference is that there are optimizations implemented in JavaScript engines that only apply when using the pseudoclassical pattern. Think of the pseudoclassical pattern a probably faster version of the prototypal pattern; the object relations in both examples are the same.
var Car = function(loc) {
this.loc = loc;
};
Car.prototype.move = function() {
this.loc++;
};
var amy = new Car(1);
amy.move();
var ben = new Car(9);
ben.move();
Finally, it should not be too difficult to realize how object oriented programming can be done. There are two sections.
One section that defines common properties/methods in the prototype (chain).
And another section where you put the definitions that distinguish the objects from each other (loc variable in the examples).
This is what allows us to apply concepts like superclass or subclass in JavaScript.
Feel free to add or edit. Once more complete I could make this a community wiki maybe.
I believe that #Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.
var A = function() {};
A.prototype = {
_instance_var: 0,
initialize: function(v) { this._instance_var = v; },
x: function() { alert(this._instance_var); }
};
EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.
As discussed in other answers, it's really a performance consideration because the function in the prototype is shared with all of the instantiations - rather than the function being created for each instantiation.
I put together a jsperf to show this. There is a dramatic difference in the time it takes to instantiate the class, although it is really only relevant if you are making many instances.
http://jsperf.com/functions-in-constructor-vs-prototype
Think about statically typed language, things on prototype are static and things on this are instance related.
When you use prototype, the function will only be loaded only once into memory (independently on the amount of objects you create) and you can override the function whenever you want.

Need direction for learning Object inheritance and code clean java script

I am really fixed with JS object related concepts. For ex:
Crockford says: Objects produced from object literals are linked to Object.prototype
Now on console when I type:
// input represented with >
> var a = {};
> console.log(Object.getPrototypeOf(a));
Object {} // <-- output
> console.log(a.prototype);
undefined
Crockford says:Function objects are linked to Function.prototype (which is itself linked to Object.prototype)
> function b(){};
> console.log(Object.getPrototypeOf(b));
function()
> console.log(b.prototype);
b{}
> console.log(b.prototype.prototype);
undefined
> console.log(Object.getPrototypeOf(b.prototype));
Object {}
When I do getPrototypeOf() I get the expected output, but when I try to use the prototype property I get undefined. Cant figure out the reason.
Also for line 5 return value is function(). Can some please explain does this say ? I expected an Object to be returned.
It would be great if someone please give me insight/good links/some class diagrams(as we have in java) to follow for understanding prototypal inheritance.
Okay. Here's the thing. There are some concepts in JS that seem really convoluted at the start, but are actually really straightforward. Let's have a look at a few of them.
1) function.prototype property
When you define a function, the JS engine creates an anonymous object and binds the two using property names prototype and constructor as follows:
function foo(){}
/* Performed by JS engine internally */
// foo.prototype = {};
// foo.prototype.constructor = foo;
Therefore, only functions have .prototype.
The .prototype is used only and only when the function is invoked using the new operator.
2) References
In JS, references can be used to pass along a variable, without creating a duplicate of it. Perhaps an example might help here:
var a = 1;
var b = { val: 1 };
var c = { val: 1 };
var x;
/*variable cloned*/
x = a;
x++;
console.log(a); // 1
console.log(x); // 2
/*variable refernced*/
x = b;
x.val++;
console.log(b); // { val: 2 }
console.log(x); // { val: 2 }
/*variable cloned*/
x = c.val;
x++;
console.log(c); // { val: 1 }
console.log(x); // 2
3) object.__proto__ property
Any object created by invoking a function with the new keyword, like var x = new foo();, will have a __proto__ property on it that is the object referenced by its constructor function's .prototype property. Re-assigning foo.prototype to somethings else will not affect objects that have already been created.
In other words,
function foo(){}
// foo.prototype = {};
// foo.prototype.constructor = foo;
var x = new foo();
console.log(x.__proto__ === foo.prototype); // true
Also, when you create an object like var x = {};, it is the exact same thing as:
var x = new Object();
Therefore, x.__proto__ is the object referenced by Object.protoype.
Conclusion
How does all this add up?
foo.prototype acts as a "blueprint" for the objects created using the function foo.
When we do create an object x = new foo(), JS engine stores a reference (link) to "the blueprint that was used to make x" as the __proto__ property.
When I do getPrototypeOf() I get the expected output, but when I try to use the prototype property I get undefined. Cant figure out the reason.
Object.getPrototypeOf(...) returns the __proto__ property, not prototype.
Also for line 5 return value is function(). Can some please explain does this say ? I expected an Object to be returned.
In JS, all data types have an associated "Wrapper" function.
Similar to how x = {} is the same as x = new Object(), doing function b(){} is the same as b = new Function()
since b was created invoking a function using new, it has a __proto__ property, that is the object referenecd by its constructor function's prototype. In this case, Function.prototype, which is also Function.
Still confused? I'd recommend having a good long read at http://www.javascripttutorial.net/

Javascript Object prototype confusion (with require.js and three.js)

Essentially what I'm confused about has something to do with either my understanding of Objects / prototypes, require.js or three.js. Here's an example:
TLDR:
"wee" is an instance of "Wee" which is a wrapper/monkey patch of THREE...
Shouldn't "wee" therefore have properties and methods of THREE?
(Transitive property and whatnot: a = b = c; a = c.)
define (['three'], function () {
function WEE(){
THREE;
return THREE;
}
var test = new WEE;
console.log("test");
console.log(test);
function Wee(){
WEE.call(this);
this.prototype = new WEE();
this.width = window.innerWidth;
this.height = window.innerHeight;
this.aspectRatio = window.innerWidth / window.innerHeight;
}
var wee = new Wee();
console.log("wee");
console.log(wee);
});
This is where I start to get confused...
The 'test' log in chrome shows:
test
Object {REVISION: "66", CullFaceNone: 0, CullFaceBack: 1, CullFaceFront: 2, CullFaceFrontBack: 3…}
which is good. My goal was to create a monkey patch of three.js.
However, when I log 'wee in chrome it shows:
wee
Wee {prototype: Object, width: 1920, height: 1102, aspectRatio: 1.7422867513611615}
expanding the prototype detail thing I can see that the prototype is Wee, which is THREE- which is also good... but what's confusing me is that later in my code I do this:
var renderer = new wee.WebGLRenderer();
and it returns "undefined".
I've also tried
var renderer = wee.WebGLRenderer;
var renderer = wee.WebGLRenderer();
all of which fail with "Uncaught TypeError: undefined is not a function.
Questions:
What's going on?
What am I missing?
Why does THREE work at all in the first place, being that my define function requires it but doesn't assign it to anything?
Am I asking the right question? What would be a different way to phrase it so I can just google it next time?
This line:
this.prototype = new WEE();
creates a property on the object called prototype. It does nothing to set the underlying prototype of the object (which isn't called prototype; it's anonymous in the standard for now, some implementations call it __proto__). You might as well have called that property robert.
The prototype of an object is set (for now) in one of two ways:
If you create the object via new FunctionName, its underlying prototype is set from whatever FunctionName.prototype refers to when you use the new operator.
If you create the object via Object.create, it's whatever you pass into Object.create to assign the prototype.
So:
function Foo() {
}
Foo.prototype = {
bar: 42
};
var f = new Foo();
console.log(f.bar); // 42
And
var f = Object.create({
bar: 42
});
console.log(f.bar); // 42
But notably:
function Foo() {
this.prototype = {
bar: 42
};
}
var f = new Foo();
console.log(f.bar); // undefined
console.log(f.prototype.bar); // 42
Note that creating a property called prototype on the instance created by new Foo doesn't do anything to set the prototype of that instance.
This is one of the great confusions of JavaScript: The prototype property on functions is not the prototype of the function, it's the prototype that new will assign to an object if you create the object via new FunctionName. Objects don't have any named property that represents their prototype (for now, cross-implementation).
In ES6 (the next version of the spec), the __proto__ property accessor is very, very likely to be defined to allow us to directly access and set the prototype of an object. (It's in the draft specs, which means it's cleared multiple levels of review; I can't see it being removed at this point.) Currently SpiderMonkey (Firefox's JavaScript engine) supports that, and a couple of others may as well, but it's not standard.

Use of 'prototype' vs. 'this' in JavaScript?

What's the difference between
var A = function () {
this.x = function () {
//do something
};
};
and
var A = function () { };
A.prototype.x = function () {
//do something
};
The examples have very different outcomes.
Before looking at the differences, the following should be noted:
A constructor's prototype provides a way to share methods and values among instances via the instance's private [[Prototype]] property.
A function's this is set by how the function is called or by the use of bind (not discussed here). Where a function is called on an object (e.g. myObj.method()) then this within the method references the object. Where this is not set by the call or by the use of bind, it defaults to the global object (window in a browser) or in strict mode, remains undefined.
JavaScript is an object-oriented language, i.e. most values are objects, including functions. (Strings, numbers, and booleans are not objects.)
So here are the snippets in question:
var A = function () {
this.x = function () {
//do something
};
};
In this case, variable A is assigned a value that is a reference to a function. When that function is called using A(), the function's this isn't set by the call so it defaults to the global object and the expression this.x is effective window.x. The result is that a reference to the function expression on the right-hand side is assigned to window.x.
In the case of:
var A = function () { };
A.prototype.x = function () {
//do something
};
something very different occurs. In the first line, variable A is assigned a reference to a function. In JavaScript, all functions objects have a prototype property by default so there is no separate code to create an A.prototype object.
In the second line, A.prototype.x is assigned a reference to a function. This will create an x property if it doesn't exist, or assign a new value if it does. So the difference with the first example in which object's x property is involved in the expression.
Another example is below. It's similar to the first one (and maybe what you meant to ask about):
var A = new function () {
this.x = function () {
//do something
};
};
In this example, the new operator has been added before the function expression so that the function is called as a constructor. When called with new, the function's this is set to reference a new Object whose private [[Prototype]] property is set to reference the constructor's public prototype. So in the assignment statement, the x property will be created on this new object. When called as a constructor, a function returns its this object by default, so there is no need for a separate return this; statement.
To check that A has an x property:
console.log(A.x) // function () {
// //do something
// };
This is an uncommon use of new since the only way to reference the constructor is via A.constructor. It would be much more common to do:
var A = function () {
this.x = function () {
//do something
};
};
var a = new A();
Another way of achieving a similar result is to use an immediately invoked function expression:
var A = (function () {
this.x = function () {
//do something
};
}());
In this case, A assigned the return value of calling the function on the right-hand side. Here again, since this is not set in the call, it will reference the global object and this.x is effective window.x. Since the function doesn't return anything, A will have a value of undefined.
These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:
var A = function () {
this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance));
// {"objectsOwnProperties":"are serialized"}
Related questions:
What does it mean that JavaScript is a prototypal language?
What is the scope of a function in JavaScript?
How does the "this" keyword work?
Sidenote: There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.
JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.
As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".
Here is some code to show this subtle difference:
// x is a method assigned to the object using "this"
var A = function () {
this.x = function () { alert('A'); };
};
A.prototype.updateX = function( value ) {
this.x = function() { alert( value ); }
};
var a1 = new A();
var a2 = new A();
a1.x(); // Displays 'A'
a2.x(); // Also displays 'A'
a1.updateX('Z');
a1.x(); // Displays 'Z'
a2.x(); // Still displays 'A'
// Here x is a method assigned to the object using "prototype"
var B = function () { };
B.prototype.x = function () { alert('B'); };
B.prototype.updateX = function( value ) {
B.prototype.x = function() { alert( value ); }
}
var b1 = new B();
var b2 = new B();
b1.x(); // Displays 'B'
b2.x(); // Also displays 'B'
b1.updateX('Y');
b1.x(); // Displays 'Y'
b2.x(); // Also displays 'Y' because by using prototype we have changed it for all instances
As others have mentioned, there are various reasons to choose one method or the other. My sample is just meant to clearly demonstrate the difference.
Take these 2 examples:
var A = function() { this.hey = function() { alert('from A') } };
vs.
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Most people here (especially the top-rated answers) tried to explain how they are different without explaining WHY. I think this is wrong and if you understand the fundamentals first, the difference will become obvious. Let's try to explain the fundamentals first...
a) A function is an object in JavaScript. EVERY object in JavaScript gets an internal property (meaning, you can't access it like other properties, except maybe in browsers like Chrome), often referred to as __proto__ (you can actually type anyObject.__proto__ in Chrome to see what it references. This is just that, a property, nothing more. A property in JavaScript = a variable inside an object, nothing more. What do variables do? They point to things.
So what does this __proto__ property points to? Well, usually another object (we'll explain why later). The only way to force JavaScript for the __proto__ property to NOT point to another object is to use var newObj = Object.create(null). Even if you do this, the __proto__ property STILL exists as a property of the object, just it doesn't point to another object, it points to null.
Here's where most people get confused:
When you create a new function in JavaScript (which is an object as well, remember?), the moment it is defined, JavaScript automatically creates a new property on that function called prototype. Try it:
var A = [];
A.prototype // undefined
A = function() {}
A.prototype // {} // got created when function() {} was defined
A.prototype is TOTALLY DIFFERENT from the __proto__ property. In our example, 'A' now has TWO properties called 'prototype' and __proto__ . This is a big confusion for people. prototype and __proto__ properties are in no way related, they're separate things pointing to separate values.
You may wonder: Why does JavaScript has __proto__ property created on every single object? Well, one word: delegation. When you call a property on an object and the object doesn't have it, then JavaScript looks for the object referenced by __proto__ to see if it maybe has it. If it doesn't have it, then it looks at that object's __proto__ property and so on...until the chain ends. Thus the name prototype chain. Of course, if __proto__ doesn't point to an object and instead points to null, well tough luck, JavaScript realizes that and will return you undefined for the property.
You may also wonder, why does JavaScript creates a property called prototype for a function when you define the function? Because it tries to fool you, yes fool you that it works like class-based languages.
Let's go on with our example and create an "object" out of A:
var a1 = new A();
There's something happening in the background when this thing happened. a1 is an ordinary variable which was assigned a new, empty object.
The fact that you used the operator new before a function invocation A() did something ADDITIONAL in the background. The new keyword created a new object which now references a1 and that object is empty. Here's what happening additionally:
We said that on each function definition there's a new property created called prototype (which you can access it, unlike with the __proto__ property) created? Well, that property is being used now.
So we're now at the point where we have a freshly baked empty a1 object. We said that all objects in JavaScript have an internal __proto__ property which points to something (a1 also has it), whether it's null or another object. What the new operator does is that it sets that __proto__ property to point to the function's prototype property. Read that again. It's basically this:
a1.__proto__ = A.prototype;
We said that A.prototype is nothing more than an empty object (unless we change it to something else before defining a1). So now basically a1.__proto__ points to the same thing A.prototype points to, which is that empty object. They both point to the same object which was created when this line happened:
A = function() {} // JS: cool. let's also create A.prototype pointing to empty {}
Now, there's another thing happening when var a1 = new A() statement is processed. Basically A() is executed and if A is something like this:
var A = function() { this.hey = function() { alert('from A') } };
All that stuff inside function() { } is going to execute. When you reach the this.hey.. line, this is changed to a1 and you get this:
a1.hey = function() { alert('from A') }
I won't cover why this changes to a1 but this is a great answer to learn more.
So to summarize, when you do var a1 = new A() there are 3 things happening in the background:
A totally new empty object is created and assigned to a1. a1 = {}
a1.__proto__ property is assigned to point at the same thing as A.prototype points to (another empty object {} )
The function A() is being executed with this set to the new, empty object created in step 1 (read the answer I referenced above as to why this changes to a1)
Now, let's try to create another object:
var a2 = new A();
Steps 1,2,3 will repeat. Do you notice something? The key word is repeat. Step 1: a2 will be a new empty object, step 2: its __proto__ property will point to the same thing A.prototype points to and most importantly, step 3: function A() is AGAIN executed, which means that a2 will get hey property containing a function. a1 and a2 have two SEPARATE properties named hey which point to 2 SEPARATE functions! We now have duplicate functions in same two different objects doing the same thing, oops...You can imagine the memory implications of this if we have 1000 objects created with new A, after all functions declarations take more memory than something like the number 2. So how do we prevent this?
Remember why the __proto__ property exists on every object? So that if you retrieve the yoMan property on a1 (which doesn't exist), its __proto__ property will be consulted, which if it's an object (and is most cases it is), it will check if it contains yoMan, and if it doesn't, it will consult that object's __proto__ etc. If it does, it will take that property value and display it to you.
So someone decided to use this fact + the fact that when you create a1, its __proto__ property points to the same (empty) object A.prototype points to and do this:
var A = function() {}
A.prototype.hey = function() { alert('from prototype') };
Cool! Now, when you create a1, it again goes through all of the 3 steps above, and in step 3, it doesn't do anything, since function A() has nothing to execute. And if we do:
a1.hey
It will see that a1 does not contain hey and it will check its __proto__ property object to see if it has it, which is the case.
With this approach we eliminate the part from step 3 where functions are duplicated on each new object creation. Instead of a1 and a2 having a separate hey property, now NONE of them has it. Which, I guess, you figured out yourself by now. That's the nice thing...if you understand __proto__ and Function.prototype, questions like these will be pretty obvious.
NOTE: Some people tend to not call the internal Prototype property as __proto__, I've used this name through the post to distinguish it clearly to the Functional.prototype property as two different things.
In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.
A reason to use the first form is to access "private members". For example:
var A = function () {
var private_var = ...;
this.x = function () {
return private_var;
};
this.setX = function (new_x) {
private_var = new_x;
};
};
Because of javascript's scoping rules, private_var is available to the function assigned to this.x, but not outside the object.
The first example changes the interface for that object only. The second example changes the interface for all object of that class.
The ultimate problem with using this instead of prototype is that when overriding a method, the constructor of the base class will still refer to the overridden method. Consider this:
BaseClass = function() {
var text = null;
this.setText = function(value) {
text = value + " BaseClass!";
};
this.getText = function() {
return text;
};
this.setText("Hello"); // This always calls BaseClass.setText()
};
SubClass = function() {
// setText is not overridden yet,
// so the constructor calls the superclass' method
BaseClass.call(this);
// Keeping a reference to the superclass' method
var super_setText = this.setText;
// Overriding
this.setText = function(value) {
super_setText.call(this, "SubClass says: " + value);
};
};
SubClass.prototype = new BaseClass();
var subClass = new SubClass();
console.log(subClass.getText()); // Hello BaseClass!
subClass.setText("Hello"); // setText is already overridden
console.log(subClass.getText()); // SubClass says: Hello BaseClass!
versus:
BaseClass = function() {
this.setText("Hello"); // This calls the overridden method
};
BaseClass.prototype.setText = function(value) {
this.text = value + " BaseClass!";
};
BaseClass.prototype.getText = function() {
return this.text;
};
SubClass = function() {
// setText is already overridden, so this works as expected
BaseClass.call(this);
};
SubClass.prototype = new BaseClass();
SubClass.prototype.setText = function(value) {
BaseClass.prototype.setText.call(this, "SubClass says: " + value);
};
var subClass = new SubClass();
console.log(subClass.getText()); // SubClass says: Hello BaseClass!
If you think this is not a problem, then it depends on whether you can live without private variables, and whether you are experienced enough to know a leak when you see one. Also, having to put the constructor logic after the method definitions is inconvenient.
var A = function (param1) {
var privateVar = null; // Private variable
// Calling this.setPrivateVar(param1) here would be an error
this.setPrivateVar = function (value) {
privateVar = value;
console.log("setPrivateVar value set to: " + value);
// param1 is still here, possible memory leak
console.log("setPrivateVar has param1: " + param1);
};
// The constructor logic starts here possibly after
// many lines of code that define methods
this.setPrivateVar(param1); // This is valid
};
var a = new A(0);
// setPrivateVar value set to: 0
// setPrivateVar has param1: 0
a.setPrivateVar(1);
//setPrivateVar value set to: 1
//setPrivateVar has param1: 0
versus:
var A = function (param1) {
this.setPublicVar(param1); // This is valid
};
A.prototype.setPublicVar = function (value) {
this.publicVar = value; // No private variable
};
var a = new A(0);
a.setPublicVar(1);
console.log(a.publicVar); // 1
Every object is linked to a prototype object. When trying to access a property that does not exist, JavaScript will look in the object's prototype object for that property and return it if it exists.
The prototype property of a function constructor refers to the prototype object of all instances created with that function when using new.
In your first example, you are adding a property x to each instance created with the A function.
var A = function () {
this.x = function () {
//do something
};
};
var a = new A(); // constructor function gets executed
// newly created object gets an 'x' property
// which is a function
a.x(); // and can be called like this
In the second example you are adding a property to the prototype object that all the instances created with A point to.
var A = function () { };
A.prototype.x = function () {
//do something
};
var a = new A(); // constructor function gets executed
// which does nothing in this example
a.x(); // you are trying to access the 'x' property of an instance of 'A'
// which does not exist
// so JavaScript looks for that property in the prototype object
// that was defined using the 'prototype' property of the constructor
In conclusion, in the first example a copy of the function is assigned to each instance. In the second example a single copy of the function is shared by all instances.
What's the difference? => A lot.
I think, the this version is used to enable encapsulation, i.e. data hiding.
It helps to manipulate private variables.
Let us look at the following example:
var AdultPerson = function() {
var age;
this.setAge = function(val) {
// some housekeeping
age = val >= 18 && val;
};
this.getAge = function() {
return age;
};
this.isValid = function() {
return !!age;
};
};
Now, the prototype structure can be applied as following:
Different adults have different ages, but all of the adults get the same rights.
So, we add it using prototype, rather than this.
AdultPerson.prototype.getRights = function() {
// Should be valid
return this.isValid() && ['Booze', 'Drive'];
};
Lets look at the implementation now.
var p1 = new AdultPerson;
p1.setAge(12); // ( age = false )
console.log(p1.getRights()); // false ( Kid alert! )
p1.setAge(19); // ( age = 19 )
console.log(p1.getRights()); // ['Booze', 'Drive'] ( Welcome AdultPerson )
var p2 = new AdultPerson;
p2.setAge(45);
console.log(p2.getRights()); // The same getRights() method, *** not a new copy of it ***
Hope this helps.
I know this has been answered to death but I'd like to show an actual example of speed differences.
Function directly on object:
function ExampleFn() {
this.print = function() {
console.log("Calling print! ");
}
}
var objects = [];
console.time('x');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('x');
//x: 1151.960693359375ms
Function on prototype:
function ExampleFn() {
}
ExampleFn.prototype.print = function() {
console.log("Calling print!");
}
var objects = [];
console.time('y');
for (let i = 0; i < 2000000; i++) {
objects.push(new ExampleFn());
}
console.timeEnd('y');
//x: 617.866943359375ms
Here we're creating 2,000,000 new objects with a print method in Chrome. We're storing every object in an array. Putting print on the prototype takes about 1/2 as long.
Prototype is the template of the class; which applies to all future instances of it. Whereas this is the particular instance of the object.
Let me give you a more comprehensive answer that I learned during a JavaScript training course.
Most answers mentioned the difference already, i.e. when prototyping the function is shared with all (future) instances. Whereas declaring the function in the class will create a copy for each instance.
In general there is no right or wrong, it's more a matter of taste or a design decision depending on your requirements. The prototype however is the technique that is used to develop in an object oriented manner, as I hope you'll see at the end of this answer.
You showed two patterns in your question. I will try to explain two more and try to explain the differences if relevant. Feel free to edit/extend.
In all examples it is about a car object that has a location and can move.
Object Decorator pattern
Not sure if this pattern is still relevant nowadays, but it exists. And it is good to know about it.
You simply pass an object and a property to the decorator function. The decorator returns the object with property and method.
var carlike = function(obj, loc) {
obj.loc = loc;
obj.move = function() {
obj.loc++;
};
return obj;
};
var amy = carlike({}, 1);
amy.move();
var ben = carlike({}, 9);
ben.move();
Functional Classes
A function in JavaScript is a specialised object. In addition to being invoked, a function can store properties like any other object.
In this case Car is a function (also think object) that can be invoked as you are used to do. It has a property methods (which is an object with a move function). When Car is invoked the extend function is called, which does some magic, and extends the Car function (think object) with the methods defined within methods.
This example, though different, comes closest to the first example in the question.
var Car = function(loc) {
var obj = {loc: loc};
extend(obj, Car.methods);
return obj;
};
Car.methods = {
move : function() {
this.loc++;
}
};
var amy = Car(1);
amy.move();
var ben = Car(9);
ben.move();
Prototypal Classes
The first two patterns allow a discussion of using techniques to define shared methods or using methods that are defined inline in the body of the constructor. In both cases every instance has its own move function.
The prototypal pattern does not lend itself well to the same examination, because function sharing via a prototype delegation is the very goal for the prototypal pattern. As others pointed out, it is expected to have a better memory footprint.
However there is one point interesting to know:
Every prototype object has has a convenience property constructor, which points back to the function (think object) it came attached to.
Concerning the last three lines:
In this example Car links to the prototype object, which links via constructor to Car itself, i.e. Car.prototype.constructor is Car itself. This allows you to figure out which constructor function built a certain object.
amy.constructor's lookup fails and thus is delegated to Car.prototype, which does have the constructor property. And so amy.constructor is Car.
Furthermore, amy is an instanceof Car. The instanceof operator works by seeing if the right operand's prototype object (Car) can be found anywhere in the left operand's prototype (amy) chain.
var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
return obj;
};
Car.prototype.move = function() {
this.loc++;
};
var amy = Car(1);
amy.move();
var ben = Car(9);
ben.move();
console.log(Car.prototype.constructor);
console.log(amy.constructor);
console.log(amy instanceof Car);
Some developers can be confused in the beginning. See below example:
var Dog = function() {
return {legs: 4, bark: alert};
};
var fido = Dog();
console.log(fido instanceof Dog);
The instanceof operator returns false, because Dog's prototype cannot be found anywhere in fido's prototype chain. fido is a simple object that is created with an object literal, i.e. it just delegates to Object.prototype.
Pseudoclassical patterns
This is really just another form of the prototypal pattern in simplified form and more familiar to do those who program in Java for example, since it uses the new constructor.
It does the same as in the prototypal pattern really, it is just syntactic sugar overtop of the prototypal pattern.
However, the primary difference is that there are optimizations implemented in JavaScript engines that only apply when using the pseudoclassical pattern. Think of the pseudoclassical pattern a probably faster version of the prototypal pattern; the object relations in both examples are the same.
var Car = function(loc) {
this.loc = loc;
};
Car.prototype.move = function() {
this.loc++;
};
var amy = new Car(1);
amy.move();
var ben = new Car(9);
ben.move();
Finally, it should not be too difficult to realize how object oriented programming can be done. There are two sections.
One section that defines common properties/methods in the prototype (chain).
And another section where you put the definitions that distinguish the objects from each other (loc variable in the examples).
This is what allows us to apply concepts like superclass or subclass in JavaScript.
Feel free to add or edit. Once more complete I could make this a community wiki maybe.
I believe that #Matthew Crumley is right. They are functionally, if not structurally, equivalent. If you use Firebug to look at the objects that are created using new, you can see that they are the same. However, my preference would be the following. I'm guessing that it just seems more like what I'm used to in C#/Java. That is, define the class, define the fields, constructor, and methods.
var A = function() {};
A.prototype = {
_instance_var: 0,
initialize: function(v) { this._instance_var = v; },
x: function() { alert(this._instance_var); }
};
EDIT Didn't mean to imply that the scope of the variable was private, I was just trying to illustrate how I define my classes in javascript. Variable name has been changed to reflect this.
As discussed in other answers, it's really a performance consideration because the function in the prototype is shared with all of the instantiations - rather than the function being created for each instantiation.
I put together a jsperf to show this. There is a dramatic difference in the time it takes to instantiate the class, although it is really only relevant if you are making many instances.
http://jsperf.com/functions-in-constructor-vs-prototype
Think about statically typed language, things on prototype are static and things on this are instance related.
When you use prototype, the function will only be loaded only once into memory (independently on the amount of objects you create) and you can override the function whenever you want.

Categories