全局范围中的类在重新分配的方法中实际上指的是“ this”?

时间:2018-09-29 10:44:39

标签: javascript class ecmascript-6

我发现这段JavaScript代码很奇怪。

class Person {
    constructor(name) {
        this.name = name;
    }
    speakName() {
        console.log(this.name);
    }
}

var person = new Person("John");
person.speakName(); // John

var speakName = person.speakName;
speakName();        // Error

我从 Person 类中创建了一个名为 person 的对象。直接调用内部方法可以正常工作,但是当我将speakName重新分配给全局变量 var talkName 时,它给了我这个例外:

  

无法读取未定义的属性“名称”

因此,我认为重新分配的可变speakName 是指全局对象(Node.js中为全局对象,浏览器JavaScript中为窗口),但这不是两者。< / p>

class Person {
    constructor(name) {
        this.name = name;
    }
    speakName() {
        // console.log(this.name);
        if(typeof global !== "undefined") {
            console.log(this == global);    // false
        }
        if(typeof window !== "undefined") {
            console.log(this == window);    // false
        }
    }
}

那么,“这个”到底指的是什么?我以为这是全局对象,但似乎不是。谁能解释这个?

1 个答案:

答案 0 :(得分:-1)

来自MDN:The body of a class is executed in strict mode

这意味着this is not automatically assigned to the global object when unset的值,而是简单地保留为undefined。这是您在运行此代码时看到的确切错误

class Person {
    constructor(name) {
        this.name = name;
    }
    speakName() {
        console.log(this.name);
    }
}

var person = new Person("John");
person.speakName(); // John

var speakName = person.speakName;
speakName();        // Error - this is undefined

将此与以下示例进行比较:

var person = {
    fullName: "Fred Flintstone", //changed from "name" to avoid collision with the global name property
    speakName: function() { //this function is in the default "loose" mode
        console.log("My name is: " + this.fullName);
    }
}

var strictPerson = {
    fullName: "Barney Rubble",
    speakName: function() {
        "use strict"; // <-- electing to use strict mode for this function
        console.log("My name is: " + this.fullName);
    }
}

person.speakName(); // <-- "this" refers to "person"
var speakName = person.speakName;
speakName();// <-- "this" refers to the global object

strictPerson.speakName(); // <-- "this" refers to "strictPerson"
var speakNameStrict = strictPerson.speakName;
speakNameStrict();// <-- "this" is undefined

如您所见,在默认的执行模式下,确实this被重新分配,但是在严格模式下,您将获得与使用class相同的结果。