[英]Why does 'this' and 'prototype' behave differently on constructor vs instance?
I'm trying to understand why this and prototype behave differently in the constructor vs. the new instance. 我试图理解为什么这个和原型在构造函数和新实例中表现不同。 In the following code Aircraft.range returns undefined.
在以下代码中,Aircraft.range返回未定义。 I can't understand why it doesn't return 2,000 like the new instance.
我不明白为什么它不像新实例一样返回2000。
function Aircraft() { this.range = '2,000 Km'; } let mustang = new Aircraft(); console.log('Aircraft.range ', Aircraft.range); console.log('mustang.range ', mustang.range);
This attempt using prototype produces the same result. 尝试使用原型会产生相同的结果。
function Aircraft() {} Aircraft.prototype.range = '2,000 Km'; let mustang = new Aircraft(); console.log(Aircraft.range); console.log(mustang.range);
**** Update **** ****更新****
I've read many articles on prototypes and instances but theory only goes so far. 我已经阅读了许多有关原型和实例的文章,但理论仅是到目前为止。 This is a specific question used to work out the mechanics of these ideas.
这是一个特定的问题,用于解决这些想法的问题。 The answers I received helped me understand this concept better than a dozen articles talking about theory.
我收到的答案比十几篇有关理论的文章更好地理解了这个概念。 I'm sure that these answers will help other people trying to learn the fundamentals of Javascript.
我敢肯定,这些答案将对尝试学习Javascript基础的其他人有所帮助。
Here's a simple explanation for all three cases: 以下是这三种情况的简单说明:
this.range
means that range
is a property of the created instance only. this.range
表示range
仅是创建的实例的属性。 Aircraft.prototype.range
means that range
is a property of all instances you'll create because it's defined in the constructor's prototype. Aircraft.prototype.range
意味着range
是您将创建的所有实例的属性,因为它是在构造函数的原型中定义的。 Aircraft.range
means that range
is a property of the constructor (because functions are objects) and is not related to instances. Aircraft.range
表示range
是构造函数的属性(因为函数是对象),与实例无关。 Instances can only access that property by using this.constructor.range
. this.constructor.range
来访问该属性。 Something that really helped me understand this was understanding exactly what the new
keyword does. 真正帮助我了解这一点的是完全了解
new
关键字的功能。
new Aircraft
means: new Aircraft
意味着:
{}
") {}
”) Aircraft
function with the object as this
(setting .range
on that object to "2,000 Km"
Aircraft
与对象的功能this
(设置.range
该对象上,以"2,000 Km"
Aircraft.prototype
Aircraft.prototype
You could sort of implement it yourself like this: 您可以这样自己实现:
function _new ( constructor ) {
var instance = {};
constructor.call( instance );
instance.prototype = constructor.prototype;
return instance;
}
_new( Aircraft )
is roughly equivalent to new Aircraft()
. _new( Aircraft )
大致等同于new Aircraft()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.