this指向及如何改变this指向
一、this指向问题
1、普通函数调用方式的this指向
function fun(){
console.log(this); // window
};
fun(); //相当于window.fun(),此时this指向 window,window被省略
2、对象方法调用方式的this指向
var obj = {
fun: function () {
console.log(this); // obj
}
}
obj.fun(); //此时调用this指向obj对象
3、构造函数调用方式this指向
function Person(age, name) {
this.age = age;
this.name = name
console.log(this) // 此时 this 分别指向 Person 的实例对象 p1 p2
}
var p1 = new Person(18, '张三')
var p2 = new Person(18, '李四')
4、事件绑定方法this指向
<body>
<button id="btn">点我啊</button>
<script>
var oBtn = document.getElementById("btn");
oBtn.onclick = function() {
console.log(this); // 此时this指向oBtn对应的‘点我啊’按钮
}
</script>
</body>
5、定时器this指向
setInterval(function () {
console.log(this); // 此时的this指向window
}, 1000);
二、改变this指向方法
1、call() 方法
语法: fun.call(thisA, a, b, …)
function fun(a, b) {
return a + '\' + b + '\' + this.c;
}
var obj = {};
obj.c = 1000;
console.log( fun.call(obj, 10, 100) ); // 10\100\1000
此时fun的this指向obj,传递的参数为10,100,执行a + ‘’ + b + ‘’ + this.c,得到结果10\100\1000
2、apply() 方法
apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是单一对象
语法: fun.apply(thisA,[a,b,c,…])
3、bind()方法
bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上 。
this.a = 9
var obj = {
a: 81,
getX: function() { return this.a; }
}
obj.getX() //81
var obj1 = obj.getX
obj1() //9
obj1.bind(obj)() //81
以上只是个人理解,有不同理解请各位大佬指教