javascript - "the prototype belongs to the class not the instance"在javascript中是什么意思?

标签 javascript prototype-programming

我问的问题是:

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/

相关文章:

javascript - AngularJS - CSS 动画仅以一种方式工作

Javascript - 原型(prototype)数组打印测试错误

javascript - JQuery 使用自定义选择器和逻辑进行验证

javascript - 单击时使用 JavaScript 打开一个新的(空)选项卡,然后添加 URL

javascript - 无法使用 ng-packagr 获取已发布的包

javascript - 如何在 JS 中调用 thunk 来访问子对象属性?

javascript - 原型(prototype)声明的函数不是函数

javascript - mb.YTPlayer jQuery 插件中背景视频静音的问题

prototypejs - 在 JavaScript 中创建另一个对象的实例

Javascript:一旦 'class/object' 变为 'extended' ,是否可以使用不同的基数 'class/object' 重新扩展它?