var Person = { name : 'alice', say : function(txt1,txt2) { console.info(txt1+txt2); console.info(this.name); }}var Dog = { name : 'tom', say : functio ...
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