Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion about javascript exercise

Tags:

javascript

oop

I just got Javascript: The Good Parts by Douglas Crockford and I'm having some difficulty understanding one of his examples regarding prototypes. The code in the book reads as follows:

if (typeof Object.create !== "function") {
    Object.create = function(o) {
        var F = function () {}
        F.prototype = o;
        return new F;
    };
}

I'm assuming that this code is used to target a function's prototype. But why use such a complex approach? Why not just use variable.prototype? Crockford is the leading expert on Javascript so I'm sure there is a good reason for using this model. Can anyone help me understand it better? Any help would be appreciated.

like image 728
dopatraman Avatar asked Aug 03 '11 21:08

dopatraman


2 Answers

In ECMAScript 3, the new operator was the only standard way to set the [[Prototype]] internal property of an object, in this case, Crockford is just using a temporary constructor function F for that purpose.

The o argument of that method, is set as the prototype property of the temporary constructor, and by invoking new F(); it builds a new empty object that inherits from F.prototype (see this question for more details about how new works).

For example:

var a = { a: 1 };
var b = Object.create(a); // b inherits from a
b.a; // 1

In the above example, we can say that the b's internal [[Prototype]] property points to a.

Object.getPrototypeOf(b) === a; // true

In other words, b inherits from a.

With the same example, we could use an empty constructor, e.g.:

 function F(){}
 F.prototype = a;

 var b = new F(); // b again inherits from a (F.prototype)

Remember also that the prototype property of functions is different than the [[Prototype]] property that all objects have, the prototype property of functions is used when they are called with the new operator, to build a new object that inherits from that property.

Also, be aware that now, the ECMAScript 5 Standard is being implemented, and this shim, doesn't conform 100% with the spec, in fact, there are some features of the standard Object.create method that cannot be emulated on ES3.

See also:

  • JavaScript prototype limited to functions?
like image 193
Christian C. Salvadó Avatar answered Sep 20 '22 00:09

Christian C. Salvadó


var bar = Object.create(foo)

vs.

var bar = new Object()

the first bar has foo as its prototype; the second has Object as its prototype.

like image 23
Claudiu Avatar answered Sep 19 '22 00:09

Claudiu