函数还可访问bind方法创建新函数。无论使用哪种方法调用,bind方法创建的新函数与原始函数的函数体相同,新函数被绑定到指定的对象上。
<button id="testClick">Click Me!</button>
<script>
console.log('---------------在事件处理中绑定指定的上下文-------------------------');
var button = {
clicked: false,
click: function () {
this.clicked = true;
if (button.clicked) {
console.log('The button has been clicked.');
}
}
};
var elem = document.getElementById('testClick');
elem.addEventListener('click', button.click.bind(button));
var boundFunction = button.click.bind(button);
if (boundFunction != button.click) {
console.log('Calling bind creates a completely new Function');
}
</script>
代码的秘诀在于使用bind()方法:
elem.addEventListener('click', button.click.bind(button));
所有函数都可以访问bind方法,可以创建并返回一个新函数,并绑定在传入的对象上,(在本例中,绑定在button对象上)。不管如何调用该函数,this均被设置为对象本身。被绑定的函数与原始函数行为一致,函数体一致。
无论何时单击按钮,都将调用绑定的函数,函数上下文是button对象。从下面的if语句可以看出:调用bind方法不会修改原始函数,而是创建一个全新的函数:
var boundFunction = button.click.bind(button);
if (boundFunction != button.click) {
console.log('Calling bind creates a completely new Function');
}
参考《JavaScript忍者秘籍》