美文网首页
call,apply,bind详解

call,apply,bind详解

作者: bingo_LBJ | 来源:发表于2017-08-19 13:28 被阅读0次

一、call

可以让call()中的对象调用当前对象所拥有的function。你可以使用call()来实现继承:写一个方法,然后让另外一个新的对象来继承它(而不是在新对象中再写一次这个方法)

call 用法实例

使用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 同上
  function Toy(name, price) {
    Product.call(this, name, price);
    this.category = 'toy';
  
  var cheese = new Food('feta', 5);
  var fun = new Toy('robot', 40);  

用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()  
    }
  }).call(animals[i],i) 
}

使用call方法调用函数并且指定上下文的'this'

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); // Douglas Crockford Is An Awesome Javascript Developer

二 、apply

在调用一个存在的函数时,你可以为其指定一个 this对象。 this
指当前对象,也就是正在调用这个函数的对象。 使用 apply, 你可以只写一次这个方法然后在另一个对象中继承它,而不用在新对象中重复写该方法。apply与 call()非常相似,不同之处在于提供参数的方式。apply使用参数数组而不是一组参数列表(原文:a named set of parameters)。apply 可以使用数组字面量(array literal),如 fun.apply(this, ['eat', 'bananas']),或数组对象, 如 fun.apply(this, new Array('eat', 'bananas'))。
你也可以使用 arguments 对象作为 argsArray参数。
arguments是一个函数的局部变量。 它可以被用作被调用对象的所有未指定的参数。 这样,你在使用apply函数的时候就不需要知道被调用对象的所有参数。 你可以使用arguments来把所有的参数传递给被调用对象。 被调用对象接下来就负责处理这些参数。从 ECMAScript 第5版开始,可以使用任何种类的类数组对象,就是说只要有一个 length属性和[0...length)范围的整数属性。例如现在可以使用 NodeList 或一个自己定义的类似 {'length': 2, '0': 'eat', '1': 'bananas'}形式的对象。
需要注意:Chrome 14 以及 Internet Explorer 9 仍然不接受类数组对象。如果传入类数组对象,它们会抛出异常。

aplly 用法实例

使用apply和内置函数

 var numbers = [5, 6, 2, 3, 7];
  /* using Math.min/Math.max apply */
var max = Math.max.apply(null, numbers);
 /* This about equal to Math.max(numbers[0], ...) or       Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);

在"monkey-patching"中使用apply

var originalfoo = someobject.foo;
someobject.foo = function() {
  //在调用函数前干些什么
  console.log(arguments);
  //像正常调用这个函数一样来进行调用:
  originalfoo.apply(this,arguments);
  //在这里做一些调用之后的事情。
}

三、bind

bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体(在 ECMAScript 5 规范中内置的call
属性)。当新函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。一个绑定函数也能使用new
操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数

相关文章

网友评论

      本文标题:call,apply,bind详解

      本文链接:https://www.haomeiwen.com/subject/smpgrxtx.html