【问题标题】:Javascript object prototype arrow function not working [duplicate]Javascript对象原型箭头功能不起作用[重复]
【发布时间】:2020-06-10 21:06:26
【问题描述】:

我认为这真的很简单,但由于某种原因它不起作用。我想做一个点函数来检查多个对象属性:

Object.prototype.hasOwnProperties = (properties) => { return properties.every(prop => this.hasOwnProperty(prop)) }

var test = {
    foo: 'bar',
    baz: 'boz'
}

result = test.hasOwnProperties(['foo', 'baz'])
console.log(result)

我希望它返回true,因为test 包含foobaz,但它返回false。为什么以及如何解决?

【问题讨论】:

    标签: javascript ecmascript-6 prototype


    【解决方案1】:

    You must not use arrow functions (=>) when working with prototypes and referencing their instances (i.e. this) because arrow functions are lexically scoped

    Object.prototype.hasOwnProperties = function(properties) { return properties.every(prop => this.hasOwnProperty(prop)) }
    
    var test = {
        foo: 'bar',
        baz: 'boz'
    }
    
    result = test.hasOwnProperties(['foo', 'baz'])
    console.log(result)

    【讨论】:

    • 我美丽的箭:(
    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2015-10-23
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多