javascript - JS 绑定(bind)对象函数调用自身

标签 javascript

<分区>

我创建了一个对象,该对象具有一个函数,该函数使用“this”关键字引用自身的一个属性。

如果我正常调用它,它工作正常。但是,如果我将它作为参数传递给 forEach 函数,它就不起作用,除非我将它绑定(bind)到自身。

有没有更优雅的解决方案?

这是一个例子:

var foobar = {

    foo : function (number) {
       this.bar();
    },

    bar : function () {
        return "string"
    }
};

foobar.foo(0);

[1,2,3].forEach(foobar.foo); //won't work

[1,2,3].forEach(foobar.foo.bind(foobar)); //works

fiddle :http://jsfiddle.net/q29yatc2/

最佳答案

@Christos已提供a good explanation为什么会发生。但是,在回答您的问题时,更优雅的解决方案 会将 foobar 作为 thisArg of forEach 传递:

[1, 2, 3].forEach(foobar.foo, foobar);

Documentation说:

If a thisArg parameter is provided to forEach, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

演示: http://jsfiddle.net/q29yatc2/4/

关于javascript - JS 绑定(bind)对象函数调用自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27963866/

相关文章:

javascript - Sencha ExtJS 4 链接组合框问题

javascript - 使用 php 提交表单,通过 javascript 检查电子邮件

javascript - 如何在两个文本(css 或 js)之间放置线

Javascript - 在使用参数之前检查参数

javascript - 当 MongoDB 插入日期时,它会将其转换为 UTC

javascript - 从 JSON 中获取特定对象

javascript - .net 中的 WebBrowser 控件如何处理 ObjectForScripting

php - HTML5 网络存储与 Cookie

javascript - 如何用Jquery调整进度条?

javascript - 在 JS/JQuery 中查找 toArray 创建的数组中元素的索引