我问的问题是:
Why cant I declare a constructor instantiate an object and then access the prototype?
你可以看到我已经标记了答案。我理解他的回答,但我对他的意思有点困惑:
The prototype belongs to the class, not the instance:
这是否意味着 javascript 在这个例子中有一个类?我以为javascript是无类的?它只有函数构造函数...函数构造函数在什么时候成为一个类?是当您使用 .prototype 访问器向其中添加其他成员时吗?
最佳答案
实际上class
是一个OOP术语,而不是真正的javascript。这意味着原型(prototype)属于构造函数
。所以在
function MyConstructor(prop){
this.foo = prop || 'foo';
}
MyConstructor.prototype.bar = 'allways bar';
var mc1 = new MyConstructor('I am mc1'),
mc2 = new MyConstructor('I am mc2');
alert(mc1.bar) ; //=> allways bar
alert(mc2.bar) ; //=> allways bar
alert(mc1.foo) ; //=> I am mc1
alert(mc2.foo) ; //=> I am mc2
bar
属于构造函数 (MyConstructor
) 原型(prototype)。对于每个实例,它都将始终是“allways bar”。 foo
是一个实例属性(默认值为“foo”),可以为每个实例分配不同的值。
关于javascript - "the prototype belongs to the class not the instance"在javascript中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6150684/