且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

了解构造函数调用模式中的"this"

更新时间:2022-12-14 11:15:10

在javascript中,当在实例上调用在原型上定义的函数时;函数内部的"this"表示(想像被替换为-)该实例(或在其原型链中具有原型的拥有对象).

In javascript, when a function defined on a prototype is called on an instance; "this" inside the function means (think like it is replaced with-) that instance (or the owning object having the prototype in its prototype chain).

在您的情况下,构造函数(也是原型上的一个函数)被一个新创建的对象(其关键字为"new")调用为"this".

In your case the constructor (which is also a function on the prototype) is called with a newly created object as "this" with the "new" keyword.

var Quo = function(string) {
    first = this; //this is the newly created instance
    this.status = string;// first this
};

然后还首先分配完全相同的实例.

Then first is also assigned the exact same instance.

在同一实例上调用get_status时,它将再次替换为该实例;

When get_status is called on the same instance, this is again replaced with the instance;

Quo.prototype.get_status = function() {
    second = this; //this is myQuo
    return this.status;//second this
};

这一次分配了相同的实例.

and this time second is assigned the same instance.

执行myQuo.get_status()与;

doing myQuo.get_status() is same as;

Quo.prototype.get_status.call(myQuo)

因此,这两个"this"关键字引用同一对象.

Therefore these two "this" keywords refer to the same object.

如果两个变量指向同一个实例,则进行"==="检查可以很好地进行比较.获得构造函数名称只是告诉您它们是使用特定的构造函数名称构造的,而不是其他.可以使两个不同的对象具有相同的构造函数名称.

Doing the "===" check is perfectly fine to compare if two variables point to the same instance. Getting the constructor name just tell you they were constructed with a specific constructor name, not else. It is possible to make two different objects with the same constructor name.