[英]JavaScript: why I get false instead of true in my code of property owner searching?
I learn JavaScript and play with it. 我学习JavaScript并使用它。 Why I get
false
instead of true
in my code of property owner searching? 为什么在我的财产所有者搜索代码中我得到的是
false
而不是true
? 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
Because b.constructor.prototype != a
. 因为
b.constructor.prototype != a
。 You will want to use Object.getPrototypeOf
to follow the prototype chain. 您将要使用
Object.getPrototypeOf
跟随原型链。
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. 您的代码只适用于构造函数和new运算符,在所有其他情况下,它都会出错,因为它不会直接从构造函数原型继承。 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. 请注意,重写Object.prototype是一个坏主意,因为它会使所有for循环感到困惑。 So one may set enumerable to false, or one simply make it static...
因此,可以将enumerable设置为false,或者只是将其设置为静态...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.