JavaScript中的call、apply和bind方法

2019-05-08  本文已影响0人  流浪的三鮮餡

JavaScript中的call(), apply()和bind()是Function.prototype下的方法,都是用于改变函数运行时上下文,最终的返回值是你调用的方法的返回值,若该方法没有返回值,则返回undefined。这几个方法很好地体现了js函数式语言特性,在js中几乎每一次编写函数式语言风格的代码,都离不开call和apply。

1. call()

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"

2. apply()

需要注意:Chrome 14 以及 Internet Explorer 9 仍然不接受类数组对象。如果传入类数组对象,它们会抛出异常。

function.apply(thisArg, [argsArray])
var numbers = [5, 6, 2, 3, 7];

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

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

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

console.log(min);
// expected output: 2

3. bind()

function.bind(thisArg[, arg1[, arg2[, ...]]])
var module = {
  x: 42,
  getX: function() {
    return this.x;
  }
}

var unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

var boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
上一篇 下一篇

猜你喜欢

热点阅读