Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:为什么在我的属性所有者搜索代码中得到false而不是true?_Javascript - Fatal编程技术网

JavaScript:为什么在我的属性所有者搜索代码中得到false而不是true?

JavaScript:为什么在我的属性所有者搜索代码中得到false而不是true?,javascript,Javascript,我学习JavaScript并使用它。为什么在我的业主搜索代码中得到false而不是true?我犯了什么错 /* Get the object containing the property. */ Object.prototype.where = function (propName){ return this.hasOwnProperty(propName) ? this : (this.constructor.prototype ? null : this.where.bind(th

我学习JavaScript并使用它。为什么在我的业主搜索代码中得到
false
而不是
true
?我犯了什么错

/* 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

因为
b.constructor.prototype!=a
。您将希望使用来跟踪原型链

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
您的代码只与构造函数和新操作符一起工作,在所有其他情况下都会出错,因为它不会直接从构造函数原型继承。最好是查找原型链:

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");

请注意,重写Object.prototype是个坏主意,因为它会混淆所有for循环。因此,您可以将enumerable设置为false,或者简单地将其设置为静态…

构造函数将是ObjectConstructor,请考虑不扩展对象原型,当人们这样做时,有时您可能会希望它导致全局问题!至少让它成为一个静态的
对象。where(obj,propName)
函数。为什么要将它与
对象。原型进行比较?这不允许像
Object.where({},“hasOwnProperty”)
这样的事情。