通过几个例子了解apply、call、bind的区别
var user = { name:"kim", getName:function(){ console.log(this.name); }}var func = user.getName;func(); //undefineduser.getName();// kim
我们是想打印user中的name属性,但是却打印出了undefined,why?直接执行user.getName是可以的
1.call()
var user = { name:"kim", getName:function(action, thing){ console.log(this.name + " " + action + " " + thing); }}var func = user.getName;func.call(user, 'eat', 'rice') //kim eat rice
2.apply()
var user = { name:"kim", getName:function(action, thing){ console.log(this.name + " " + action + " " + thing); }}var func = user.getName;func.apply(user, ['drive', 'car']) //kim drive car
3.bind()
var user = { name:"kim", getName:function(action, thing){ console.log(this.name + " " + action + " " + thing); }}var func = user.getName;var func1 = func.bind(user);func1('like','coding') //kim like coding