JavaScript中this详解

this 是 JavaScript 语言的一个关键字。

它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用。

function test() {
    this.x = 1;
}

上面代码中,函数 test 运行时,内部会自动有一个 this 对象可以使用。

 

一、this 的值是什么

函数的不同使用场合,this 有不同的值。

总的来说,this 就是函数运行时所在的环境对象。

 

 

二、this 的使用场景

1、作为一般函数执行

2、作为对象属性执行

3、作为构造函数执行

4、通过 call、apply、bind 调用

 

 

三、this 的判断

 

1. 作为一般函数执行时,this 指代全局对象

function test(){
    this.x = 1;
    alert(this.x);
}
test();    // 1

 

2. 作为对象属性执行时,this 指代上级对象

function test(){
    alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m();    // 1

 

3. 作为构造函数调用时,this 指代 new 出的对象

var x = 2;
function test(){
    this.x = 1;
}
var o = new test();
alert(x);        // 2
alert(o.x);        // 1

对于 new 的方式来说,this 被永远绑定在了 o 上面

 

4. call、apply、bind 调用时,this 指代第一个参数

let a = {}
let fn = function () { console.log(this) }
fn.bind().bind(a)()

上述代码中,不管我们给函数 bind 几次,fn 中的 this 永远由第一次 bind 决定,所以结果永远是 window

 

 

四、总结

 

posted @ 2019-07-04 19:13  Leophen  阅读(3044)  评论(0编辑  收藏  举报