开发者

this and protoype javascript

Why does alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?

function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototyp开发者_如何学Ce = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);


The prototype property is a property of a constructor function. It's not a property of objects created with that constructor function.

Internally any object must know what its prototype is, but it's not exposed as a property with a name.

In some implementations it may be given a weird name. In Firefox it's called __proto__, but obviously you can't rely on that working in any other browser.

http://www.packtpub.com/article/using-prototype-property-in-javascript


d is a instance, to get the prototype use:

d.constructor.prototype;


I think the drawing in http://mckoss.com/jscript/object.htm describes it (I can never remember this myself). There's a property __proto__ in Firefox that references the prototype, but other than that, going from an instance to prototype isn't done (except checking with instanceof).

this and protoype javascript

Image is borrowed from above mentioned URL.


FF and chrome can give you the parent object in __proto__ which can be accessed using d.__proto__


You shouldn't use Dog.prototype = new Animal(); Try: Dog.prototype = Animal; instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜