简体   繁体   中英

why i am unable to acces the instance properties / properties defined inside the constructor into static method

class Person{
  constructor(firstname,lastname){
    this.firstname=firstname
    this.lastname = lastname
  }

  static bio(){
    return `${this.firstname}`
  }

}

personOne = new Person('Deepak','Kumar')
console.log(Person.bio())

I am trying to access the properties I have defined inside the constructor inside the static method but I am getting undefined. hiw to access the properties inside the static method.. why I am unable to access it please explain the concept behind this.

A static method is associate to the Class not on the Object create by the class.

 class Toy{ static ToyCollection = []; constructor(color,description){ this.color = color; this.description = description; Toy.ToyCollection.push(this); } static redToy(){ return new Toy('red','Red toy'); } static BlueToy(){ return new Toy('red','Blue toy'); } static greenToy(){ return new Toy('green','Green toy'); } static Historique(){ this.ToyCollection.forEach(toy => { console.log(toy); }); } static ToyIDInformation(id){ return this.ToyCollection[id]; } ToyInformation(){ console.log('Toy color: '+this.color); console.log('Toy Description: '+this.description); } } let purpleToy = new Toy('purple','Custom toy') Toy.Historique(); console.log('------------------') let redToy = Toy.redToy(); Toy.Historique(); console.log('-------------') console.log('You can') console.log('-------------') purpleToy.ToyInformation(); console.log('-------------') console.log('But you cant') console.log('-------------') try{ purpleToy.Historique(); } catch (error) { console.error(error); } purpleToy.Historique(); console.log('-------------') console.log('neither') console.log('-------------') try{ Toy.ToyInformation(); } catch (error) { console.error(error); }

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