“原型属于该类而不是实例"是什么?在JavaScript中意味着什么? [英] What does "the prototype belongs to the class not the instance" mean in javascript?

查看:46
本文介绍了“原型属于该类而不是实例"是什么?在JavaScript中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个问题:

为什么我不能声明构造函数实例化一个对象然后访问原型吗?

您会看到我已标记答案.我理解回应,但是林先生对他的意思有些困惑:

And you can see that I have marked the answer. I understand the response but Im a bit confused as to what he means by:

The prototype belongs to the class, not the instance:

这是否意味着javascript在此示例中具有一个类?我以为javascript是无类的?它仅具有函数构造函数...函数构造函数在什么时候成为类?当您使用.prototype访问器向其添加其他成员时,是这样吗?

Does this mean that javascript has a class in this example? I thought javascript was classless? It only has function constructors... At what point does a function constructor become a class? Is it when you add other members to it using the .prototype accessor?

推荐答案

实际上 class 是OOP术语,不是真正的javascript.这意味着原型属于 constructor .所以在

Actually class is an OOP term, not really javascript. What is meant is that the prototype belongs to the constructor. So in

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 )原型.对于每个实例,它将始终为"allways bar". foo 是一个实例属性(默认值为'foo'),可以为每个实例分配一个不同的值.

bar belongs to the constructors (MyConstructor) prototype. It will always be 'allways bar', for every instance. foo is an instance property (with a default value 'foo') and can be assigned with a different value for every instance.

这篇关于“原型属于该类而不是实例"是什么?在JavaScript中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆