1.bind()
函数.bind(this指向,函数参数...)
1 函数调用bind会返回一个新的函数
2 新函数中的this指向bind的第一个参数
例:
function show() {
console.log('show');
console.log(this);
}
show();// this指向window
var obj = {
name: 'zs'
};
var fn = show.bind(obj); // 由于返回的是新函数,也可以写成
fn();// this指向obj
// 由于返回的是新函数,也可以写成↓
// var fn = show.bind(obj)();
this指向:
![](https://img-blog.csdnimg.cn/img_convert/df88e104f7fb122ffb1416ffce0d939a.png)
2. bind()行内事件this指向
<div onclick="fn(this)"> 只愿君心似我心,定不负相思意</div>
<!-- 行内绑定改变this的指向 -->
<div onclick="fn1.bind(this)()"> 你猜猜</div>
<script>
function fn(that) {
console.log(that); // 只愿君心
// console.log(this);
}
function fn1() {
console.log(this); // 你猜猜
}
</script>