JavaScript中this详解

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

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

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

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

 

1、this 的值是什么

函数的不一样使用场合,this 有不一样的值。spa

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

 

 

2、this 的使用场景

一、做为通常函数执行

二、做为对象属性执行

三、做为构造函数执行

四、经过 call、apply、bind 调用

 

 

3、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 决定,因此结果永远是 windowblog

 

 

4、总结

相关文章
相关标签/搜索