function TestClass(){
this.property = true;
}
TestClass.prototype.getValue = function(){
return this.property;
};
var test = new TestClass();
window.alert(test.prototype.getValue());
问题:
在TestClass的原型对象中添加了getValue()方法,为什么无法通过原型来访问这个方法(即test.prototype.getValue()无效),而只能通过test.getValue()来调用。小弟刚接触javascript,望各位大神指点。
首先,
prototype
是Constructor的field, instance里面根本就没有。 不妨test一下:console.log(test.prototype);
而, Instance有一个叫[[prototype]]的内部属性, 指向Constructor.prototype。
那么, 我们怎么通过[[prototype]]来访问Constructor.prototype呢?
在ECMAScript 5, 有一个method可以return [[prototype]]的值; that is,
Object.getPrototypeOf()
。Learn more on
JavaScript高级程序设计
。