clss中的this指向

137 阅读1分钟
class Foo {
    sayThis () {
        console.log(this); // 这里的 `this` 指向谁?undefined
    }
    
    exec (cb) {
        cb();
    }
    
    render () {
        this.exec(this.sayThis);
    }
}
    
var foo = new Foo();
foo.render(); // 输出结果是什么?

class 内部方法中若涉及到 this,则一定要注意。class 中的 this 永远都不会指向 window。 熟悉 function 的应该知道,function 类的实例方法,可能指向 window(在某些情况下,具体读者可自行百度,也可阅读下述例子推敲)。 而 class 则在 this 可能指向 window 的情况下,将 this 指向 undefined。如下:

class Class01 {
    constructor() {
        this.a = 'a';
    }
    geta(){
        return this.a;
    }
}
let ins01 = new Class01();
console.log( ins01.geta() ); /* a */
let obj = {};
obj.a = 'objA';
obj.geta = ins01.geta;
console.log( obj.geta() ); /* 'objA' */
window.a = 'windowA';
window.geta = ins01.geta;
/* Cannot read property 'a' of undefined */
/* 若是 function 类此处会返回 'windowA' */
try { geta() } catch ( e ) { console.error( e ); }