开发者

Best method for Prototype object oriented programming in JavaScript

I rather like the prototype way of programming and have been trying to understand it in javascript.

I saw this bit of code in The Good Parts:

function beget(o){
  function F(){
    F.prototype = o;
  };
  return new F();
};

I don't get this at all lol. If all you have to do is set the prototype to a past object, then couldn't you just do this:

var parent = {
  num = 66;
};
var child = {
  prototype: parent
};

This doesn't seem to work though, cause child.num is returned as undefined. How do you describe javascript prototype programming and what开发者_如何学运维 are your methods? Thanks guys


Personally I think the most idiomatic method is as follows:

function Parent() {
    this.value = 2;
}

function Child() {

}

Child.prototype = new Parent();

var c = new Child();
alert(c instanceof Child); // true
alert(c instanceof Parent); // true
alert(c.value); // 2


You can only add prototype to a function object. When invoked via new it will use it as its prototype.

Btw, the function you quoted is part of the new version of ECMAScript as Object.create (with an additional propertiesObject parameter).

Let me put it this way: {object} is a singleton. A function() object however is a constructor, that is, when called with new creates an instance (by executing the function's body, and using the constructor's prototype). Of course the prototype can be a function object too, and have its own prototype, etc. Specialization and Generalization means walking up and down the prototype chain.


The second example does not work because your just setting a property of an object. What you want to do is set the prototype property of a constructor function, and then create an object from that function.

var parent = {
   num : 666
};

function ChildConstructor(){
   console.log(this.num);
}
ChildConstructor.prototype = parent;

var child = new ChildConstructor();

http://jsfiddle.net/W9C3K/

Setting or changing the prototype on an object is not possible without proprietary methods.


The .prototype property has special meaning to JavaScript, but only for functions, which is why your code doesn't work.

With "protypical inheritance", you don't inherit from a base class. Instead, you start with with some object and create a new one, using the first as a prototype. Then you add properties and methods to the newly created object.

I'm not sure what you mean by "what are your methods?" Do you mean programming methodology, or something like that?

UPDATE: Your question is pretty broad, and I don't think I can do it justice with a short answer here.You might want to have a look at the SO question below, which has a good discussion of JS prototypes, as well as some links to stuff that other people have found helpful on this topic.

How does JavaScript .prototype work?


var parent = {
  num : 66
};
var child = {
   __proto__: parent
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜