0

I thought this would be really simple but it's not working for some reason. I want to make a dot function to check for multiple object properties:

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)

I expected it to return true since test contains both foo and baz but it returns false. Why and how to fix?

xendi
  • 1,831
  • 3
  • 27
  • 51

1 Answers1

2

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)
feihcsim
  • 1,138
  • 2
  • 14
  • 25