[英]Javascript - Constructor's properties & Prototype
I'm trying to understand one thing about constructors. 我试图了解有关构造函数的一件事。 Namely I don't understand how function object's properties, aka constructor's properties can't be accessed using Foo.prototype.property, example: 也就是说,我不明白如何使用Foo.prototype.property访问函数对象的属性,也就是构造函数的属性,例如:
//let's create new function object with predefined properties
function Foo() {
this.name = "Mike";
this.returnName = function() {
return 'This persons name is ' + this.name + '.';
};
};
//now let's create new object using constructor and prototypal inheritance
var mike = new Foo();
mike.returnName(); //returns "This persons name is Mike."
I understand that mike inherits properties from Foo's prototype. 我知道迈克继承了Foo原型的属性。 So these properties must be present inside of the prototype. 因此,这些属性必须存在于原型内部。 new object points toward the prototype with internal prototype link using __ proto __. 新对象使用__ proto __指向带有内部原型链接的原型。 I get that. 我明白了。 Thing that I can't get around is how this doesn't work: 我无法解决的问题是如何工作的:
Foo.prototype.returnName();
Constructor has .prototype link with prototype property and vice versa prototype has .constructor link with the Foo. 构造函数具有带有原型属性的.prototype链接,反之亦然,原型具有带有Foo的.constructor链接。
I know that calling the Foo(); 我知道调用Foo(); function first then calling for window.returnName(); 函数首先调用window.returnName(); would return the sentence, since this context is set to window. 将返回该句子,因为此上下文设置为window。
Is this because when I call the method using prototype it assigns it to the window? 这是因为当我使用原型调用该方法时,会将其分配给窗口吗? Is there any way I could access/call this constructor's property? 有什么办法可以访问/调用此构造方法的属性?
You are not specifying returnName on the prototype of Foo. 您没有在Foo的原型上指定returnName。 If you would do it like this: 如果您要这样做:
function Foo(){
this.name = "Mike";
}
Foo.prototype.returnName = function(){
return 'This persons name is ' + this.name + '.';
};
var mike = new Foo();
mike.returnName();
Things would be different. 情况会有所不同。
The function returnName
is not assigned to the prototype of Foo
. 函数returnName
未分配给Foo
的原型。 Instead it's assigned to every instance of Foo
, just like the name
is "Mike"
. 而是将其分配给Foo
每个实例,就像name
为"Mike"
。
Whenever you call new Foo()
a new context is created, this is the this
context of that instance. 每当您调用new Foo()
都会创建一个新的上下文,这就是该实例的this
上下文。
If you call Foo()
directly (without new
) this
is the global object ( window
). 如果直接(不带new
)调用Foo()
this
是全局对象( window
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.