函数内this的指向问题
函数内的this指向:this的指向是当前我们调用函数的时候确定的,调用的方式不同决定了this的指向不同,一般指向我们的调用者
不同调用方式下的this指向
- 普通函数调用
// 1. 普通函数 this 指向window
function fn() {
console.log('普通函数的this' + this);
}
window.fn(); //window可省略
- 对象方法调用
// 2. 对象的方法 this指向的是对象fn
var fn = {
sayHi: function() {
console.log('对象方法的this:' + this);
}
}
fn.sayHi();
- 构造函数调用
// 3. 构造函数 this 指向 ldh 这个实例对象 原型对象里面的this 指向的也是 ldh这个实例对象
function Star() {};
Star.prototype.sing = function() {
}
var ldh = new Star();
- 事件绑定方法
// 4. 绑定事件函数 this 指向的是函数的调用者 btn这个按钮对象
var btn = document.querySelector('button');
btn.onclick = function () {
console.log('绑定时间函数的this:' + this);
};
// 5. 定时器函数 this 指向的也是window
window.setTimeout(function () {
console.log('定时器的this:' + this);
}, 1000);
- 定时器函数
// 5. 定时器函数 this 指向的也是window
window.setTimeout(function () {
console.log('定时器的this:' + this);
}, 1000);
- 立即指向函数
// 6. 立即执行函数 this还是指向window
(function () {
console.log('立即执行函数的this' + this);
})();
具体的打印结果:
改变函数内部的this指向
JavaScript常用的三种处理函数内部this的指向问题的方法:call( ) 、apply( ) 、bind( )
三者的区别:
共同点:都可以改变this指向
不同点:
- call( )方法和apply( )方法会调用函数,并且改变函数内部的this指向
- call( )方法和apply( )方法传递的参数不一样,call( )方法传递的参数使用逗号隔开,apply( )方法使用数组的形式传递
- bind( )方法不会调用函数,可以改变函数内部this的指向
主要的应用场景:
- call( )方法经常做继承
- apply( )方法经常跟数组有关系,比如借助数学对象实现数组最大最小值问题
- bind( )方法不会调用函数,但还想改变函数内部this的指向,比如改变定时器内部的this指向
~~
上述有些地方表述可能不够严谨,欢迎交流
~~