this的指向问题
1、普通函数调用,this指向window
2、构造函数调用,this指向实例对象
3、对象方法调用,this指向 该方法所属的对象
4、通过事件绑定的方法, this指向 绑定事件的对象
5、定时器函数,this 指向window
请看栗子:
// 1、普通函数调用 3、对象方法调用 var name = '小王',age=17; var obj = { name: '小张', objAge: this.age, // this指向window myFun:function() { console.log('名字:' + this.name + '年龄:' + this.age);// this都指向该方法的对象obj } }
obj.objAge; // 17 obj.myFun; // 名字:小张 + 年龄:undefined // 2、构造函数调用
function Person(age,name) {
this.age = age;
this.name = name;
console.log(this); // this指向p1,p2
}
let p1 = new Person(12,'wyb');
let p2 = new Person(18,'www');
// 通过事件绑定的方法
<button id='btn'>按钮</button>
var btn = document.getElementById('btn');
btn.onclick = function() {
console.log(this); // 指向btn
}
// 定时器
setInterval(function(){
console.log(this); // this指向window
},2000)
划重点,敲黑板:
1、更改this指向的三个方法为call()、apply()、bind()
var name = '小王',age=17; var obj = { name: '小张', objAge: this.age, // this指向window myFun:function() { console.log('名字:' + this.name + '年龄:' + this.age);// this都指向该方法的对象obj } } var db = { name: '老板', age: 100 } obj.myFun.call(db); // 名字:老板 年龄:100 obj.myFun.apply(db); //名字:老板 年龄:100 obj.myFun.bind(db)(); //名字:老板 年龄:100
// 以上得出 bind()后面多了()外,结果返回都一致
// 所以,bind返回的是一个新的函数,必须调用才能被执行
2、对比三者传参的情况
var name = '小王',age=17; var obj = { name: '小张', objAge: this.age, myFun:function() { console.log('名字:' + this.name + '年龄:' + this.age + '来自' + formcity + '去往' + tocity); } } var db = { name: '老板', age: 100 } obj.myFun.call(db, '北京', '上海'); //名字:老板 年龄:100 来自北京去往上海 obj.myFun.apply(db, ['北京', '上海']); //名字:老板 年龄:100 来自北京去往上海 obj.myFun.bind(db, '北京', '上海')(); //名字:老板 年龄:100 来自北京去往上海 obj.myFun.bind(db, ['北京', '上海'])(); //名字:老板 年龄:100 来自北京,上海去往undefined
// 从以上的结果来看,
call、apply、bind方法的第一个参数都是this的指向对象,第二个参数「可以允许各种类型」有区别
call 是用逗号分隔开
apply 是用数组包括起来的
bind 除了返回是函数以外,它的参数和call一样
原文地址:https://www.cnblogs.com/Shd-Study/p/6560808.html
~