call(),apply() 继承

158 阅读1分钟

1、区别
call(),所有参数放到第一个参数后面,逗号分开
apply(),第二个参数是数组

var arr = [1, 2, 3]
console.log(Math.max.apply(null, arr))
console.log(Math.max.call(null, ...arr))

2、this指向
1)、this一般在函数中才有指向,指向调用函数的对象或者函数的调用者
2)、new的时候,指向new出来的对象
3)、事件中指向当前的触发对象

var name ='小王', age = 17;
var obj = {
    name: '小张',
    objAge: this.age, //当前this指向全局
    myFun: function(){
        console.log(this.name + '年龄 ' + this.age)
    }
}
console.log(obj.objAge); // 17
obj.myFun(); // 小张年龄 undefined
function Children(name, age, height){
   console.log(this, arguments); 
   // this指的是Children这个对象,arguments代表入参 [Object arguemnts]
}
let lisi = new Children('李四', 12, 170);

image.png

3、改变this指向

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); // cheese

使用 Food构造函数创建的对象实例都会拥有在 Product 构造函数中添加的 name 属性和 price 属性,但 category 属性是在Food自己的构造函数中定义的。

4、使用
1)、合并数组

var arr1 = [1, 2, 3]
var arr2 = [4, 5, 6]
Array.prototype.push.apply(arr1, arr2)
// 或者 arr1.push.apply(arr1, arr2), Array.prototype.push.apply性能好点
console.log(arr1) // [1, 2, 3, 4, 5, 6]

2)、求最大值,最小值

Math.max.apply(null, arr)
Math.min.apply(null, arr)