JS中的bind、call、apply方法

时光总嘲笑我的痴心妄想 提交于 2020-02-02 03:38:46

bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用

 call 和 apply 是为了动态改变 this 而出现的,当一个 object 没有某个方法(banana没有say方法),但是其他的有(apple有say方法),我们可以借助call或apply用其它对象的方法来操作。

function fruits() {}
fruits.prototype = {
    color: "red",
    say: function() {
        console.log("My color is " + this.color);
    }
}
 
var apple = new fruits;
apple.say();    //My color is red

banana = {
    color: "yellow"
}
apple.say.call(banana);     //My color is yellow
apple.say.apply(banana);    //My color is yellow

apply、call作用完全一样,只是接受参数的方式不太一样

var func = function(arg1, arg2) {}
func.call(this, arg1, arg2);
func.apply(this. [arg1, arg2]);

bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值, 因此也可以用它来改变函数体内this的指向。

MDN的解释是:bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

this.num = 9; 
var mymodule = {
  num: 81,
  getNum: function() { 
    console.log(this.num);
  }
};

mymodule.getNum(); // 81

var getNum = mymodule.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象

var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81

bind()的另一个最简单的用法是使一个函数拥有预设的初始参数。只要将这些参数(如果有的话)作为bind()的参数写在this后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。

function list() {
  return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// 预定义参数37
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

 

 

var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!