Objects in JavaScript (part II)

http://dmitry.baranovskiy.com/

I will not write about prototypical inheritance in JavaScript today. Instead lets take a look at one misunderstanding:

“Changing prototype on the constructor will magically update not only new objects, but also all existing ones…”

This is totally wrong. Do not trust an author who uses word “magic” while explaining JavaScript (or anything).

function C() {} //constructor

var x = new C();

C.prototype.prop = 2;

var y = new C();

alert(x.prop);

alert(y.prop);

This code will alert “2” and “2”, which kind of proves quoted concept: object xgains new property prop after it was created. Magic? Not at all. Lets look at similar example:

function C() {} //constructor

var x = new C();

C.prototype = {prop: 2};

var y = new C();

alert(x.prop);

alert(y.prop);

This will alert “undefined” and “2”. Huh?

In the first case neither of objects (x or y) have property prop. What they have is a hidden reference to prototype. (Hidden, because only interpreter internally can access it.) When you ask for property prop JavaScript can’t find it in the object itself and look for it in linked prototype object, found it there and return it. So for you, as a programmer, it is no visual difference where property is stored: in the object itself or in its prototype. When you add new property to prototype object x didn’t change. When you ask for property prop JavaScript finds it in updated prototype.

In the second case we assign new object as a prototype. Now object x still refers to the old prototype, but object y refers to new. x and y do not share prototype anymore. Obviously old prototype doesn’t have property prop. Even worse, now you lost the only access point to it. Despite these two objects were created with the same syntax they are way different.

One more thing. As you know every object by default receives propertyconstructor, which refers to its constructor (surprise). But just as propconstructor property doesn’t exists in object itself, but rather in its prototype. By rewriting prototype we rewrite constructor property as well:

alert(x.constructor); // "function C() {}"

alert(y.constructor); // "function Object() { [native code] }"

So, when you rewriting prototype you can’t rely on constructor property anymore. But rewriting prototype is a main technique of inheritance in JavaScript.

I will write about inheritance next time. 

你可能感兴趣的:(JavaScript)