处理this关键字

dealing with the this keyword

刚开始用this关键字,一直在想,为什么"this"不行呢?

var obj = {
    thas: this,
    obj2: {
        obj3: {
            thos: this,
            lol: "lol",
            pap: function() {
                console.log(obj.obj2.obj3.lol);
                console.log(this.lol);
                console.log(thos.lol);
            }
        }
    }
};

obj.obj2.obj3.pap();

看看第三个console.log()

我正在定义变量,为什么会出现这个错误:Uncaught ReferenceError: thos is not defined

我认为 thos 需要像 lol 一样引用。您使用 this.lol 访问 lol,因此要访问 thos,您必须访问 this.thos,这可能无法像 this.thos.lol 那样工作。 OOP 有时会变得很奇怪。如果您想改用 thos,请在对象外部定义它并尝试一下...

编辑:这是修改后的代码:

// this is the new line:
var thos = this;

var obj = {
    thas: this,
    obj2: {
        obj3: {
            lol: "lol",
            pap: function() {
                console.log(obj.obj2.obj3.lol);
                console.log(this.lol);
                console.log(thos.lol);
            }
        }
    }
};

obj.obj2.obj3.pap(); 

希望对您有所帮助!

您正在尝试访问不在范围内的 thospap: function() { } 创建了一个对 thos 一无所知的新函数作用域,因此您需要将其传入或执行 console.log(obj.obj2.obj3.thos.lol); 而不仅仅是 console.log(thos.lol);

this 在对象的 属性 中引用时指的是父对象。在 pap() 方法中你可以声明:

var thos = this;

那么你可以这样做:

console.log(thos.lol);

As MDN tells us:

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind method to set the value of a function's this regardless of how it's called, and ECMAScript 2015 introduced arrow functions whose this is lexically scoped (it is set to the this value of the enclosing execution context).

当函数作为对象的方法被调用时,其 this 设置为调用该方法的对象。所以,this.lol 工作正常,等于只调用 lol,因为它们都在范围内。

但是调用 thos.lol 时会发生什么?由于 this 设置了一个对象 属性 值,虚拟机认为 this 在全局范围内:

In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.

因此,您调用 thos.lol,它会看到全局对象并给您未定义的错误。尝试在控制台中 obj.obj2.obj3.thos.lol; ,你会看到未定义。尝试在控制台中 obj.obj2.obj3.thos;,你会看到全局对象。