使用bind方法确定接收者

时间:2023-07-14 20:45:32
 var buffer = {
entries : [],
add : function(s){
this.entries.push(s);
},
concat : function(){
return this.entries.join("");
}
} var source = ["867","-","5309"];
source.forEach(buffer.add); //error : entries is undefined var source = ["867","-","5309"];
source.forEach(buffer.add,buffer); //"867-5309" var source = ["867","-","5309"];
source.forEach(function(s){
buffer.add(s);
})
buffer.join(); //"867-5309"

还可以使用bind()函数,该是创建一个新函数而不是修改了buffer.add()函数,新函数的行为就像原来函数的行为,但它的接收者绑定到了buffer对象,而原有函数的接收者保持不变:

注意:提取一个方法不会将方法的接收者绑定到该方法的对象上

var source = ["867","-","5309"]; source.forEach(buffer.add.bind(buffer)); buffer.join(); //"867-5309"