【问题标题】:Keyword `this` gives an empty object in prototype of Array (Node.JS and ES6)关键字 `this` 在 Array 的原型中给出了一个空对象(Node.JS 和 ES6)
【发布时间】:2016-12-19 17:13:30
【问题描述】:

我将在我的 Node.JS 服务器应用程序中从 Array 中选择一个随机元素。我也使用 ES6 的箭头语法。在对象的原型中,我添加了一个名为random() 的函数。您可以在下面找到我的代码:

Array.prototype.random = () => {     // --> add element to prototype of `Array` object
    let rnd = Math.random();         // --> gives me a random number between 0 and 1
    let len = this.length;           // --> `this.length` gives `undefined`
    let naam = rnd * len - 1;        // --> result is `NaN`
    let numb = Math.floor(naam);     // --> `numb` is also `NaN`
    let arr = this;                  // --> `arr` contains an `Object` with none 
                                     //     properties or elements but `this` contains 
                                     //     the elements and the length.
    let el = arr[numb];              // --> `el` is `undefined`
    return el;                       // --> returns the random picked element
};

但是我调试代码时发现关键字this 给了我一个空对象。在监视列表中,我添加了值 arr,我看到了:

但是该数组包含两个元素,两个代表 API 密钥的字符串。

我的代码有什么问题?

【问题讨论】:

标签: arrays node.js ecmascript-6 prototype


【解决方案1】:

通常箭头函数不用于原型函数,因为正如您所发现的,您不会获得正确的this 来访问实例属性/方法。箭头函数从父上下文继承 this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2015-12-16
    相关资源
    最近更新 更多