1 var json = { 2 jArray: [], 3 jPush: function (c) { 4 this.jArray.push(c); 5 } 6 } 7 var examp = ["123", "~", "456"];
使用ES5给出的forEach循环examp,并且将它们添加到json中的jArray中;
1 examp.forEach(json.jPush);
这个时候会报错:
产生这种报错的原因是json.jPush方法中的this并没有指向json对象,而是指向了window.解决这个问题的方法就是给这个this找对人家.
好在forEach()提供了一个参数,专门用于指定对象的.看代码.
1 examp.forEach(json.jPush,json);
alert(json.jArray);//结果正常了是,123~456
还有另外一种方法:
1 examp.forEach(function (c) { 2 json.jPush(c); 3 }); 4 alert(json.jArray);//123~456
还可以使用bind绑定
examp.forEach(json.jPush.bind(json));
alert(json.jArray);
bind是创建了一个新函数而不是修改一个函数.新函数的行为和原来函数的行为一样,但他的接收者是我们给定的对象,而原有函数的接收者保持不变.
这意味着bind方法的使用是非常安全的,因为一个函数或方法被共享的时候,不用担心这个共享方法不会被修改掉了.