Add value using prototype in function instance
This question already has an answer here:
It should be a prototype of the constructor function, not the object this function produces:
a.prototype.three = 3;
You can't access object's prototype with the prototype
key, because prototype reference is not exposed like this. You could do it using __proto__
property though, but this is deprecated. If you need to get a prototype of the object you can make use of Object.getPrototypeOf
method:
Object.getPrototypeOf(j) === a.prototype; // true
It's a little confusing here because the word "prototype" sort of means two things. Function prototype is an object that is used when new object is constructed when the function is used like a constructor. Object prototype is a reference to the object which stores inherited methods.
J
's prototype is undefined, because you cant access it directly, so you cant directly set the property three to the prototype of j
.
This is why you are able to add properties to a'
s prorotype but not to j'
s prototype, you can try
j.three=3;
Or a.prototype.three = 3;
fiddle http://jsfiddle.net/s4g2n453/4/
链接地址: http://www.djcxy.com/p/30084.html上一篇: JavaScript原型委托功能
下一篇: 在函数实例中使用原型添加值