javascript 的 this 对象是否以我认为的方式引用新创建的对象 [英] does javascript's this object refer to newly created object in the way i think

查看:15
本文介绍了javascript 的 this 对象是否以我认为的方式引用新创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,当我们创建用于创建新对象的构造函数时,new 关键字做了三件事我将解释它,但如果我错了请纠正我我想确定我是正确的

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();

现在 new 关键字所做的第一件事是创建新对象并将其秘密链接设置为其构造函数的原型并将其传递给构造函数,现在 this 可以引用它,请注意 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 的 this 对象是否以我认为的方式引用新创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆