javascript的这个对象以我认为的方式引用新创建的对象 [英] does javascript's this object refer to newly created object in the way i think
问题描述
所以,当我们创建构造函数创建新对象新的关键字做3事情
我要解释它,但请纠正我,如果我错了我想确定我正确
So, when we create constructor function for creating new object the new keyword does 3 things I'am going to explain it but please correct me if I'am wrong i want to be sure I'am correct
首先我将创建一个构造函数
first i will create a constructor function
function ObjectCreate(){
this.a = "a";
this.b = "b";
ObjectCreate.prototype.show = function(){
alert(this.a+" "+this.b);
}
}
obj1 = new ObjectCreate();
现在的第一个关键字是create new object并设置它的构造函数原型的secret链接,传递给构造函数,现在 this
可以引用它,请注意这个
不是指obj1这一点,因为一旦构造函数完成创建对象,然后它返回新创建的对象到obj1变量。我问这个问题,因为有些人说 this
在这种情况下引用obj1对象。
now the first thing new keyword does is create new object and set its secret link to its constructor's prototype and pass it to the constructor function where now the this
can refer to it and please note this
does not refer to obj1 at this point because once constructor finished creating object only then it returns the newly created object to obj1 variable. i ask this question because some people say that this
refer to the obj1 object in this case. so am i right here.
推荐答案
在此示例中,在构造函数调用期间, obj1
未定义。在 ObjectCreate
函数返回后,将值分配给 obj1
变量。
In this example, during constructor invocation, obj1
is undefined. Value is assigned to obj1
variable after ObjectCreate
function returns.
您可以检查自己:
function ObjectCreate(){
this.a = "a";
this.b = "b";
alert(obj1); // yields "undefined"
ObjectCreate.prototype.show = function(){
alert(this.a+" "+this.b);
}
}
var obj1 = new ObjectCreate(); // note "var"
这篇关于javascript的这个对象以我认为的方式引用新创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!