5

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 object, 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.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
xralf
  • 3,312
  • 45
  • 129
  • 200
  • 1
    Check out this SO answer which explains in detail about javascript prototypal inheritance http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript/1598077#1598077 – Narendra Yadala Sep 09 '11 at 11:47
  • @xralf javascript good parts is a hard read tough to understand. I also share the same feeling. – sushil bharwani Sep 09 '11 at 12:09

2 Answers2

2

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.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
douwe
  • 1,305
  • 10
  • 12
  • I think you mean `o` instead of `0`. – pimvdb Sep 09 '11 at 11:52
  • *objects are just instances of functions* ... that's not true. When you call `new Func()`, then `this` inside function refers to an empty object which inherits from `Func.prototype`. That's all. Or maybe you just mean something different than I understand it :) – Felix Kling Sep 09 '11 at 12:46
1

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

Py.
  • 3,499
  • 1
  • 34
  • 53
  • Thank you, I will read it. I have seen this about a week ago but the site was corrupted or something, so I avoided this but now it's readable. – xralf Sep 09 '11 at 12:03