this的工作原理

JavaScript有一套完全不同于其他语言对this的处理机制。在五种不同的情况下,this指向的各不相同。

全局范围内

this;

当在全局环境内使用this时,它会指向全局变量(window).

var foo='bar';
console.log(this.foo)//'bar'
console.log(window.foo)//'bar'

上面代码中的this和window是等价关系

函数调用

foo()

函数正常被调用(不带new)时,里面的this指向的是全局作用域

foo='bar'

function testThis(){
    this.foo='foo'    
}

console.log(this.foo)//'bar'
testThis()
console.log(this.foo)//'foo'

上述代码中的testThis()函数中的this指的是全局变量,所以才可以更改全局变量foo的值

方法调用

test.foo();

当有对象调用方法时,this指向调用它的对象

var obj={
    foo:'bar',
    logFoo:function(){
        console.log(this.foo)
    }
}

obj.logFoo();//'bar'

调用构造函数

new foo();

如果函数倾向于和new关键词一起使用,则我们称这个函数是构造函数。在函数内部,this指向新创建的对象。

foo = "bar";

function testThis() {
     this.foo = "foo";
}

console.log(this.foo); //logs "bar"
new testThis();
console.log(this.foo); //logs "bar"
console.log(new testThis().foo); //logs "foo"

注意:在严格模式下(strict mode),不存在全局变量,这种情况下this将会是undefined

Last modification:October 19th, 2019 at 04:46 pm
如果觉得我的文章对你有用,请随意赞赏