简体   繁体   中英

How to access prototype property from within javascript class?

I am knew to javascript , please excuse my rather basic question. How can I use a property from within my class, as in the sample code below?

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;

Using this.myProperty throws the error Cannot convert undefined or null to object

Use this. :

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

That will get the property from the object. If the object doesn't have its own copy of the property, it will get it from the object's prototype.

Or if you want to get it from the prototype every time, be explicit:

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

Side note: const is a new thing, as of ES2015. If you're using ES2015 (and it looks like you're using NodeJS, which means you can if you're using v6 or later), you can write your class more simply using class notation:

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;

Note that if you want myProperty to be on the prototype, you do still need to assign it the "clunky" way. But you may want to create that property in the constructor instead.


Side note 2: Unless you change myProperty later, I strongly recommend using this.myProperty.key1 or this.myProperty.key2 and not using this.myProperty[Object.keys(this.myProperty)[0]] , which is hard to read, chaotic (undefined behavior, the order of the keys returned by Object.keys is not specified, not even in ES2015), and extra work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM