javascript - 如何在 JavaScript 中使用 "this"

标签 javascript mootools this

我有这段代码:

this.json.each(function(obj, index) {
    var li = new Element('li');
    var a = new Element('a', {
        'href': '#',
        'rel': obj.id,
        events: {
            'click': function(e) {

                this.doSteps(this.step + 1); // <-- causing issue

            }
        }   
    });
    var img = new Element('img', {
        'src': imgd + obj.img,
        'alt': obj.name                        
    });
    img.inject(a);
    a.inject(li);
    li.inject(ul);
});

我在控制台中收到“this.doSteps 不是函数”的错误。有人可以帮我解决这个问题并解释一下解决方案吗?

提前致谢。

最佳答案

您需要绑定(bind)this,因此函数的作用域引用了正确的this

'click': function(e) {
    this.doSteps(this.step + 1);
}.bind(this)

这是 MooTools 的方式。

关于javascript - 如何在 JavaScript 中使用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993472/

相关文章:

javascript - 在不离开页面和 bootstrapValidator 的情况下发送联系表

jquery - Mootools相当于jQuery的toggle()?

java - 编写android代码时此处理程序的用途是什么?

javascript - 解决/拒绝 $http 中的 promise 不起作用。

javascript - 分割文本避免某些情况(Javascript)

Ajax 登录表单 - 浏览器不会保存密码

javascript - jQuery 设置 input.value = input.title (或其他输入属性)

java - 从设计的角度来看 "Leaking this"

javascript - 跳出 javascript 嵌套的 async.each 循环但继续主循环

javascript - Mootools 使用 For(...in Array) 时的问题