关于JS call ,apply, bind之间的用法以及区别
call, apply, bind 主要实现的功能是改变this的指向.
在正常情况下 console.log(this) 输出的内容是 window 对象
第一个call函数
<script>
// 改变函数内this指向 js提供了三种方法 call() apply() bind()
var o = {
name: 'andy'
}
function fn(a, b){
console.log(this);
console.log(a + b);
};
fn.call(o, 1, 2);
// call第一个可以调用函数 第二个可以改变函数内的this 指向
function Father(uname, age, sex){
this.uname = uname;
this.age = age;
this.sex = sex;
}
function Son(uname, age, sex){
Father.call(this, uname, age, sex);
}
var son = new Son('刘德华', 18, '男');
console.log(son);
</script>
第二个 apply() 与call的区别主要是 apply后面加的是类数组
<script>
// apply()应用 运用的意思
var o = {
name: 'andy'
};
function fn(arr) {
console.log(this);
console.log(arr); // pink
};
fn.apply(o, ['pink']);
var arr = [1, 66, 3, 99, 4];
var arr1 = ['red', 'pink'];
// The Math.max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);
console.log(max, min);
</script>
MDN有更加详细的内容https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
第三个 bind() 可看作绑定函数
// bind() 绑定 捆绑的意思 var o = { name: 'andy' }; function fn(a, b) { console.log(this); console.log(a + b); } var f = fn.bind(o, 1, 2) fn(); var btn1 = document.querySelector('button'); btn1.onclick = function() { this.disabled = true; // 这个this 指向的是 btn 这个按钮 // var that = this; setTimeout(function() { // that.disabled = false; // 定时器函数里面的this 指向的是window this.disabled = false; // 此时定时器函数里面的this 指向的是btn }.bind(this), 3000); // 这个this 指向的是btn 这个对象 } // bind改变this指向后不会调用函数

浙公网安备 33010602011771号