英文:
How does public instances associated with prototypes in Javascript's Classes?
问题
我们知道在JavaScript中,类只是函数,而类只是对其基于原型的继承的一种抽象、语法糖,或者你想怎么称呼都可以。例如:
class foo {
bar() {}
}
被转换为:
function foo() {}
foo.prototype.bar = function() {};
但如果我们使用一个公共实例,比如
class foo {
bar = "Hello World";
}
我们不能像这样访问bar
实例属性:
foo.prototype.bar
(undefined)
我知道我们必须创建一个新的实例才能访问它,像这样:
var instance = new foo();
console.log(instance.bar); // "Hello World"
但不知何故,bar
属性必须内置在foo
的原型中,那它在哪里呢?
学习一下ES6内部是如何使用公共实例的。
英文:
we know that classes are just functions in javascript and classes is just an abstraction, syntactic sugar, whatever you want to call it, over its prototype-based inheritance. For example:
class foo {
bar() {}
}
is transformed to:
function foo() {}
foo.prototype.bar = function() {};
but if we use a public instance as
class foo {
bar = "Hello World";
}
we cannot access the bar
instance properies as
foo.prototype.bar
(undefined)
I know we have to create a new instance to access it like:
var instance = new foo();
console.log(instance.bar); // "Hello World"
but somehomw bar
property must be baked in foo
's proptotye, so where is it?
learn how pubilc instance is used internally by ES6
答案1
得分: 2
这些字段不会放在原型上,而是直接附加到类的每个实例上。
在foo类内部的字段声明bar = "Hello World";
中,当您创建foo的实例时,JavaScript会自动在其构造函数中将bar分配给该实例。因此,它等同于这样
class foo {
constructor() {
this.bar = "Hello World";
}
}
这就是为什么您无法通过foo.prototype.bar访问bar,因为它不是原型的一部分。它是每个从该类实例化的对象都独有的实例变量。
bar属性并没有"嵌入"到foo的原型中。它直接附加到从foo类实例化的每个对象上。
英文:
These fields are not placed on the prototype. Instead, they are directly attached to each instance of the class
With the field declaration bar = "Hello World";
inside your foo class, when you create an instance of foo, JavaScript automatically assigns bar to that instance within its constructor. So it is equivalent to this
class foo {
constructor() {
this.bar = "Hello World";
}
}
That's why you cannot access bar through foo.prototype.bar as it's not part of the prototype. It is an instance variable that is unique to each object instantiated from the class.
The bar property isn't "baked" into foo's prototype. It is directly attached to each object instantiated from the foo class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论