I'm reading this book and there is a chapter about prototypes with this hard to understand paragraph and code snippet.
When you make a new o开发者_Python百科bject, you can select the object that should be its prototype. The mechanism that JavaScript provides to do this is messy and complex, but it can be significantly simplified. We will add a beget method to the Object function. The beget method creates a new object that uses an old object as its prototype.
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
var another_stooge = Object.beget(stooge);
Could you please explain this code, why is this good etc.? Which resource would you recommend to study prototypes? Here is it quite difficult.
If you do:
Object.beget(oldObject);
The old object is the o passed to the function. The next thing is the creation of the new object. This happens with:
var F = function(){};
This creates new function F, capitalized just to show it is meant as a class that should be called with new. Next the old object is set als the prototype of this class and a new instance of F is returned.
F.prototype = o;
return new F();
What you should realise is that, in JavaScript (not having classes), objects are just instances of functions.
I always found the MDN doc on JavaScript instructive, for me, this one covers prototyp well: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model
精彩评论