[英]Dot-notation for properties within Javascript constructors
I'm working through a text book and a lesson introduces the use of dot notation when defining a constructor.我正在阅读一本教科书,一堂课介绍了在定义构造函数时使用点表示法。 (It is understood that there is other syntax to use to name a property.) When experimenting with permutations of the lesson, an outcome causes some confusion.
(可以理解,还有其他语法可用于命名属性。)在尝试对课程进行排列时,结果会引起一些混乱。
One outcome is expected, undefined, from the following example:来自以下示例的未定义结果是预期的:
function person(){
person.thing = 2;
}
console.log(person.thing);
// outcome: undefined
However, an alternative experiment with first creating an object from the constructor produces an unexpected outcome for the value of person.thing
:然而,首先从构造函数创建一个对象的替代实验为
person.thing
的值产生了意想不到的结果:
function person(){
person.thing = 2;
}
var bob = new person();
console.log(bob.thing);
// outcome: undefined
console.log(person.thing);
// outcome: 2
Why is the value for the property person.thing
now 2 after a differently named object, bob
, was created from the constructor?为什么在从构造函数创建不同名称的对象
bob
之后,属性person.thing
的值现在是 2?
person
always refers to that function object. person
总是指那个函数对象。 When you call the person
function, it actually runs so it places that property on the object.当您调用
person
函数时,它实际上会运行,以便将该属性放在对象上。
This is no different the function putting a property on any other object, like this:这与将属性放在任何其他对象上的函数没有什么不同,如下所示:
var myObj = {} function person() { myObj.thing = 2 } console.log("person.thing:", person.thing) // undefined console.log("myObj.thing:", myObj.thing) // undefined var bob = new person() console.log("bob.thing:", bob.thing) // undefined console.log("person.thing:", person.thing) // undefined console.log("myObj.thing:", myObj.thing) // 2
So the only difference is that we're now adding the thing
property to the myObj
object instead of the person
function object.所以唯一的区别是我们现在将
thing
属性添加到myObj
对象而不是person
函数对象。
So person
never has any relationship to the object being created by the constructor function... it is the constructor function.所以
person
永远不会与构造函数创建的对象有任何关系......它是构造函数。
Within the constructor function, the way to access the object being created is by using the this
keyword.在构造函数中,访问正在创建的对象的方法是使用
this
关键字。 So if you did this.thing = 2
, then bob.thing
would be 2
.所以如果你做了
this.thing = 2
,那么bob.thing
就是2
。
instead of using person而不是使用人
function person(){
person.thing = 2;
}
var bob = new person();
console.log(bob.thing);
// outcome: undefined
console.log(person.thing);
// outcome: 2
change it to this改成这个
function person(){
this.thing = 2;
}
var bob = new person();
console.log(bob.thing);
// outcome: 2
console.log(person.thing);
// outcome: undefined
did you notice the OUTCOME?
你注意到结果了吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.