簡體   English   中英

如何從javascript類中訪問原型屬性?

[英]How to access prototype property from within javascript class?

我對javascript有所了解,請原諒我的基本問題。 如何在我的課程中使用屬性,如下面的示例代碼所示?

function MyClass() {
  // nothing special
}

MyClass.prototype.myProperty = {
  key1: 'some value 1',
  key2: 'some value 2',
};

My Class.prototype.myFunction = function myFunction() {
  // I need to retrieve the first value of myProperty
  const x = myProperty[Object.keys(myProperty)[0]] + 10; // won't work
  return x;
};

module.exports = MyClass;

使用this.myProperty引發錯誤Cannot convert undefined or null to object

this.

MyClass.prototype.myFunction = function myFunction() {
  const x = this.myProperty[Object.keys(this.myProperty)[0]] + 10;
  // -------^^^^^-----------------------^^^^^
  return x;
};

那將從對象獲得屬性。 如果對象沒有自己的屬性副本,它將從對象的原型中獲取它。

或者,如果您想每次從原型中獲取它,請明確說明:

MyClass.prototype.myFunction = function myFunction() {
  const p = MyClass.prototype.myProperty;
  const x = p[Object.keys(p)[0]] + 10;
  return x;
};

旁注:從ES2015開始, const是新事物。 如果您使用的是ES2015(看起來好像您使用的是NodeJS,這意味着您可以使用v6或更高版本),則可以使用class符號更簡單地編寫class

class MyClass {
  constructor() {
    // nothing special
  }
  myFunction() {
    const x = this.myProperty[Object.keys(this.myProperty)[0]] + 10;
    return x;
  }
}
MyClass.prototype.myProperty = {
  key1: 'some value 1',
  key2: 'some value 2',
};

module.exports = MyClass;

請注意,如果希望myProperty包含在原型中,則仍然需要為它分配“笨拙”的方式。 但是您可能想在構造函數中創建該屬性。


旁注2:除非稍后更改myProperty ,否則我強烈建議使用this.myProperty.key1this.myProperty.key2而不要使用this.myProperty[Object.keys(this.myProperty)[0]] ,這很難閱讀,混亂(不確定的行為,未指定Object.keys返回的鍵順序,甚至在ES2015中也未指定)以及額外的工作。

暫無
暫無

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

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