javascript - 在内部函数中消除歧义

标签 javascript

内部函数有时需要引用外部函数的this。 JavaScript 是否有一个广泛使用的习惯用法?我想出了一个解决方案,涉及将 this 分配给另一个变量:

Object.defineProperty(Array.prototype, 'set', {
    enumerable: false,
    value: function (a) {
        this.length = 0
        var this1 = this
        a.forEach(function (x) {
            this1.push(x)
        })
    }
})

但我不确定这是否是最简洁或最惯用的解决方案。

最佳答案

我个人使用 that 作为变量名,而不是 this1,但除此之外,它既干净、传统又符合 Javascript 的习惯。

Douglas Crockford似乎也推荐使用 that

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

过去,我也看到有人使用 self

关于javascript - 在内部函数中消除歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24566514/

相关文章:

javascript - 无法访问 skyDrive 文件夹

javascript - 清算系统通知

javascript - Morris 条形图,1 条线显示 2 种颜色,负值和正值

javascript - 如何使用 jQuery 获取 select2 下拉列表的占位符值

javascript - 检索 Google Chrome 扩展程序 ID 的最佳方法是什么?

javascript - 将不透明度设置为所有图 block ,选定的图 block 除外

javascript - 对话框中的多行标题?

javascript - 仅对 div 中的最新输出行进行样式设置

javascript - 在加载所有 ajax 调用后如何调用函数?

javascript - 第一次访问时,Meteor 会跳转到页面上的某些点