js中call、apply、bind的区别

var Person = {
name : 'alice',
say : function(txt1,txt2) {
console.info(txt1+txt2);
console.info(this.name);
}
}

var Dog = {
name : 'tom',
say : function(txt1,txt2) {
console.info(txt1+txt2);
console.info(this.name);
}
}
var arr = ['hello','hi'];
Person.say('hello','hi');
Dog.say('wang~','wang2~');
Person.say.call(Dog,'hello','hi');//Person.say内部的this指向了Dog,多个参数用逗号隔开
Person.say.apply(Dog,arr);//第二个参数是数组,参数数量可以是未知的
var PersonSay = Person.say.bind(Dog,'hello','hi');//不会立即执行,触发返回函数才会执行
PersonSay();



>>>hellohi
>>>alice
>>>wang~wang2~
>>>tom
>>>hellohi
>>>tom
>>>hellohi
>>>tom
>>>hellohi
>>>tom
posted @ 2018-04-11 20:27  Alice_Xu  阅读(208)  评论(0编辑  收藏  举报