核心提示:this指向的4种场景。之前一直对js里的this的指向搞不明白,特地花了时间去学习了this到底指向什么,于是把this出现的场景做了总结,this指向主要分为四类:1.有对象就指向调用对象:var...
this指向的4种场景。之前一直对js里的this的指向搞不明白,特地花了时间去学习了this到底指向什么,于是把this出现的场景做了总结,this指向主要分为四类:
1.有对象就指向调用对象:
var myObject = {value: 100}; myObject.getValue = function () { console.log(this.value); // 输出 100 // 输出 { value: 100, getValue: [Function] }, // 其实就是 myObject 对象本身 console.log(this); return this.value; }; console.log(myObject.getValue()); // => 100
harry有话说:在对象myObject上绑定方法,在方法中this就指向对象myObject。
2.没调用对象就指向全局对象:
var myObject = {value: 100}; myObject.getValue = function () { var foo = function () { console.log(this.value) // => undefined console.log(this);// 输出全局对象 global }; foo(); return this.value; }; console.log(myObject.getValue()); // => 100
harry有话说:这里嵌套函数foo并没有直接绑定的对象,所以函数内的this指向全局对象global。
3.用new构造就指向新对象:
var SomeClass = function(){ this.value = 100; } var myCreate = new SomeClass(); console.log(myCreate.value); // 输出100
harry还有话要说:myCreate就是调用对象
4.通过apply或call或bind来改变this的所指:
var myObject = {value: 100}; var foo = function(){ console.log(this); }; foo(); // 全局变量 global foo.apply(myObject); // { value: 100 } foo.call(myObject); // { value: 100 } var newFoo = foo.bind(myObject); newFoo(); // { value: 100 }
harry总结一下好了:apply(),call(),bind()方法,将this指向函数的第一个参数对象。