0

I learn JavaScript and play with it. Why I get false instead of true in my code of property owner searching? What is my mistake?

/* Get the object containing the property. */
Object.prototype.where = function (propName){ return this.hasOwnProperty(propName) ? this :
    (this.constructor.prototype ? null : this.where.bind(this.constructor.prototype, propName)());};

let a = {foo : 123}, b = Object.create(a), c = a == b.where('foo');

process.stdout.write(c.toString()); // false
Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • constructor will be *Object* – Jonas Wilms Jun 03 '17 at 09:49
  • Consider not augmenting the Object prototype, when people do that it leads to global problems sometimes https://www.fxsitecompat.com/en-CA/docs/2015/string-prototype-contains-has-been-renamed-to-includes/ – Olga Jun 03 '17 at 09:51
  • You may want https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf – Jonas Wilms Jun 03 '17 at 09:51
  • [Don't define `Object.prototype` methods](https://stackoverflow.com/q/13296340/1048572)! At least make it a static `Object.where(obj, propName)` function. – Bergi Jun 03 '17 at 09:51

2 Answers2

0

Because b.constructor.prototype != a. You will want to use Object.getPrototypeOf to follow the prototype chain.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0
a=Object.create(b);
//constructor: Object
//constructor.prototype: Object.prototype

//really inherits from: b

a = new b();
//constructor: b
//constructor.prototype: b.prototype

//really inherits from: b.prototype

Your code just works with constructor functions and the new operator, in all the other cases it goes wrong, as it does not inherit from the constructors prototype directly. It would be better to look up the prototype chain instead:

Object.where = function (obj,propName){ 
  return obj.hasOwnProperty(propName) ? 
   obj :
(!Object.getPrototypeOf(obj) ? null : Object.where(Object.getPrototypeOf(obj), propName));
};

Object.where(Object.create({a:0}),"a");

Note that overriding Object.prototype is a bad idea, as it confuses all for loops. So one may set enumerable to false, or one simply make it static...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    Why do you compare to `Object.prototype`? That doesn't allow things like `Object.where({}, "hasOwnProperty")`. – Bergi Jun 03 '17 at 10:14