js 中call、apply、bind方法的使用

大家好,又到了博览知识的时候,今天给大家说的是jsvascript中的call和apply的使用方法。。。

在 javascript 中,call 和 apply 都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部 this 的指向。
JavaScript 的一大特点是,函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。

对于 apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。例如,有一个函数定义如下:

var fun = function(arg1, arg2) {
};

就可以通过如下方式来调用:

fun.call(this, arg1, arg2);
或者
fun.apply(this, [arg1, arg2]);

其中 this 是你想指定的上下文,它可以是任何一个 JavaScript 对象,call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里。
示例:

function fun() {
  this.color = "red";
}
fun.prototype = {
  say: function() {
    console.log("My color is " + this.color);
  }
}
var apple = new fun;
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

利用这一特点,可以实现继承
代码如下所示:
/父类/

function Parent(add,net,no,teacher) {
    this.add = add;
    this.net = net;
    this.no = no;
    this.teacher = teacher
}

/子类/

function Child(name,age,sex,id) {
    this.name = name;
    this.sex = sex;
    this.age = age;
    this.id = id;
    Parent.call(this,"山东","www.baidu.com","1608","ccy"); 
   //这个时候的Parent中的this已经被Child所代替
}
var child = new Child("fangMing","18","男","10086");
console.log(child.add);

bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值

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() 方法与 apply 和 call 很相似,也是可以改变函数体内 this 的指向。
MDN的解释是:bind()方法会创建一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数。

见识浅薄,如有错误,忘各位大神指点。。。

你可能感兴趣的:(js 中call、apply、bind方法的使用)