簡體   English   中英

JavaScript:為什么在所有者搜索代碼中我得到的是假而不是真?

[英]JavaScript: why I get false instead of true in my code of property owner searching?

我學習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 您將要使用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

您的代碼只適用於構造函數和new運算符,在所有其他情況下,它都會出錯,因為它不會直接從構造函數原型繼承。 最好改為查找原型鏈:

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,或者只是將其設置為靜態...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM