bind改变函数内部this指向的方式整理
之前一直比较纠结bind的使用就把各种形式的函数都测试了一遍
- 点击事件
//点击事件
document.querySelector('div').onclick = function () {
console.log(this);
}.bind(新的指向)
- 自调用函数
//自调用函数
(function () {
console.log(this);
}.bind(新的指向)())
//因为bind不会调用函数所以要用在bind(新的指向)的后边自己加个()调用
- 回调函数
//回调函数
var time = setInterval(function name(params) {
console.log(this);
clearInterval(time)
}.bind(新的指向), 500)
//直接在回调函数的{ }后面加就可以
- 对象上的方法
//对象上的方法
var obj = {
sey:function () {
console.log(this);
}.bind(新的指向)
}
obj.sey()
- 构造函数 构造函数改变this指向将无法拥有原型对象 pototype
//构造函数 的原型对象pototype 的方法 可以改变this指向
//构造函数
document.body.name = 'body'
var Test = function (name) {
this.name = name
console.log(this);
}
Test.prototype.sey=function(){
console.log(this.name);
}.bind(document.body)
var test = new Test('小明')
Test() // this 是window
test.sey() // this document.body