js apply 和 call

区别:

apply()方法调用具有给定this值的函数,并arguments作为数组(或类数组对象)(参数为数组)

call 和 apply 能够改变函数运行时的上下文(context),改变this的指向

apply语法:

function.apply(thisArg, [argsArray])

thisArg:可选,如果是null并且undefined将被全局对象替换,this调用function函数时,可以指定其他对象。this指当前对象,即调用对象,改变函数Function内部 this 的指向,继承funtion对象中的方法

argsArray:可选的。一个类数组的对象

返回:使用指定的this值和参数调用函数的结果

//当thisArg为空,运行上下文为全局对象
var numbers = [5, 6, 2, 3, 7];

var max = Math.max.apply(null, numbers);

console.log(max);
// expected output: 7

 

function Person(name,sex) {
    this.name = name;
    this.sex = sex;
}

function Animal(name,sex,age) {
    Person.apply(this,arguments); //this为Animal上下文,this调用Person方法时,apply动态改变Person类里面的this指向,
    this.age=age;               //Animal对象的this代替Person类里面的this对象,劫持Person对象的属性,方法,继承name,sex属性
}
var people = new Animal("xuesheng","man",10);
console.log(people.name);//xuesheng
console.log(people.sex);//man
console.log(people.age);//10

apply追加数组

var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.log(array); // ["a", "b", 0, 1, 2]

apply内置函数 最大值和最小值

// min/max number in an array
var numbers = [5, 6, 2, 3, 7];

// using Math.min/Math.max apply
var max = Math.max.apply(null, numbers);
console.log(max);//7

var min = Math.min.apply(null, numbers);
console.log(min);//2

call语法 

call()接受参数列表,同时apply()接受单个参数数组。(参数为列表)

function.call(thisArg, arg1, arg2, ...)
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);
// expected output: "cheese"

更多理解:https://www.runoob.com/w3cnote/js-call-apply-bind.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值