JS Function.prototype.apply()和call()

翻译总结:apply()call()

fun.apply(thisArg,[argsArray])

fun.call(thisArg[, arg1[, arg2[, ...]]])

两者的用法很相近,实现的功能是将某一方法fun或者某一对象内部的某个方法fun应用在另一个对象thisArg上,并且避免重复定义这个要用的方法,原理是为要调用的那个方法fun中的this指定为需要这个方法的对象。两者最主要的区别是apply接受的参数是a single array of arguments,而call接受的参数是an argument list。

apply()

下面例子将Math中的max方法应用在number数组上,获得数组中的最大值。

var numbers = [5, 6, 2, 3, 7];
var max = Math.max.apply(null, numbers); //null也可以写成{},这里不能使用call,因为numbers是一个数组
// This about equal to Math.max(numbers[0], ...)
// or Math.max(5, 6, ...)

下面这个例子将apply用于构造函数

Function.prototype.construct = function(aArgs) {
  var fConstructor = this, fNewConstr = function() { 
    fConstructor.apply(this, aArgs); 
  };
  fNewConstr.prototype = fConstructor.prototype;
  return new fNewConstr();
};

function MyConstructor() {
  for (var nProp = 0; nProp < arguments.length; nProp++) {
    this['property' + nProp] = arguments[nProp];
  }
}

var myArray = [4, 'Hello world!', false];
var myInstance = MyConstructor.construct(myArray);

console.log(myInstance.property0 + ',' + myInstance.property1 + ',' + myInstance.property2); // logs "4,Hello world!,false"
console.log(myInstance instanceof MyConstructor); // logs 'true'
console.log(myInstance.constructor);              // logs 'MyConstructor'


call()

下面这个例子示意了call的基本用法,为方法greet()中的this指定为对象i

function greet() {
  var reply = [this.person, 'Is An Awesome', this.role].join(' ');
  console.log(reply);
}

var i = {
  person: 'Douglas Crockford', role: 'Javascript Developer'
};

greet.call(i);

下面这个例子示意了利用call()调用了匿名函数。

var animals = [
  { species: 'Lion', name: 'King' },
  { species: 'Whale', name: 'Fail' }
];

for (var i = 0; i < animals.length; i++) {
  (function(i) {
    this.print = function() {
      console.log('#' + i + ' ' + this.species
                  + ': ' + this.name);
    }
    this.print();
  }).call(animals[i], i);
}

下面这个例子示意了call()在构造函数中的应用。

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0) {
    throw RangeError('Cannot create product ' +
                      this.name + ' with a negative price');
  }
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
console.log(cheese);//Food {name: "feta", price: 5, category: "food"}
console.log(fun);//Toy {name: "robot", price: 40, category: "toy"}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值