apply ,call , bind的区别
call() 与apply()只有一个区别,就是 call()
方法接受的是一个参数列表,而 apply()
方法接受的是一个包含多个参数的数组。
call(); 传递参数类型 直接返回调用结果
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
apply ();传递具体参数类型,第二个参数只能传递数组
var num = [1,3,12,11,54];
Math.max.apply(window,num); //使用null 也可以第一个参数
console.log(Math.max.apply(null,num));
call() 传递引用类型,传递值,经常做父类继承,可以改变this的指向
bind()
方法创建一个新的函数,在 bind()
被调用时,这个新函数的 this
被指定为 bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
function title(){
setInterval(function(){
console.log('hello world');
},1000);
}
title.bind(this) //如果直接这样,等到你老了,他也不会执行
title.bind(this)() //加上调用的括号就可以执行了
所以bind使用的场景就是当我们想要某一个事件等待某个时刻在开始执行的时候,就可以使用我们的bind方法
bind() 不会直接调用,需要手动调用
arr.forEach(function(value,index,self){
}) 不可以遍历DOM,不可以使用continue,break
// forEach本身不能遍历DOM,但是在通过call追加上了Array的数组方法之后就可以对DOM元素进行遍历,而for循环可以对任意的元素数值进行遍历 \
var arr = [1,32,43,22,12,45];
var bb = arr.filter(function(value,index,self){
return value>3; // 条件判断
})
console.log(bb); //输出结果32,43,22,12,45
every()只有都为真,返回为真
var a = arr.every(function(value,index,self){
console.log(value,index);
// return true;
});
console.log(a);
some()只要有一个为真,返回就为真
var b = arr.some(function(value,index,self){
// console.log(value,index);
return value > 0;
});
console.log(b);
var arr = [1,32,43,22,12,45];
//默认reduce从左边开始
var c = arr.reduce(function(prev,now,index,self){
console.log(prev,now);
return prev + now; //求和
},0);
// reduceRight从右边开始
var c = arr.reduceRight(function(prev,now,index,self){
console.log(prev,now);
return prev + now;
},0);
console.log(c);
转载自:https://juejin.cn/post/7040684111870033927