1 var buffer = { 2 entries : [], 3 add : function(s){ 4 this.entries.push(s); 5 }, 6 concat : function(){ 7 return this.entries.join(""); 8 } 9 } 10 11 var source = ["867","-","5309"]; 12 source.forEach(buffer.add); //error : entries is undefined 13 14 15 var source = ["867","-","5309"]; 16 source.forEach(buffer.add,buffer); //"867-5309" 17 18 var source = ["867","-","5309"]; 19 source.forEach(function(s){ 20 buffer.add(s); 21 }) 22 buffer.join(); //"867-5309"
还可以使用bind()函数,该是创建一个新函数而不是修改了buffer.add()函数,新函数的行为就像原来函数的行为,但它的接收者绑定到了buffer对象,而原有函数的接收者保持不变:
注意:提取一个方法不会将方法的接收者绑定到该方法的对象上
1 var source = ["867","-","5309"]; 2 source.forEach(buffer.add.bind(buffer)); 3 buffer.join(); //"867-5309"