简体   繁体   中英

Issue with using getters and setters

I'm trying to learn about getters and setters. I'm actually having trouble understanding the idea.

I wrote this simple code, but it's not working.

const person = {
  _age: 18,
  _drive: false,
    
  get drive() { 
    console.log(person._age)
    return this._age       
  },

  set drive(value) {
    console.log(value)
    this._drive = (value >= 21)
  }
}
    
console.log(person._drive)

I'm running the code using node. It's always returning false. How come?

But I think I didn't get the idea.

  • GET for me is just to collect the value that I'm going to work with.
  • SET is to set this value into somewhere.

Is that right?

Since ECMAScript 2015 there are classes.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes I believe you are looking for something like

class Person {
  
   constructor(){
     this.age = 18;
     this.drive = false;
   }

   canDrive(){
     return this.drive;
   }

   setAge(age){
     this.age = age;
     this.drive = (age >= 21);
   }

}

const person = new Person();
console.log(person.canDrive());
person.setAge(21)
console.log(person.canDrive());

Demo: https://es6console.com/kd6b7cp0/

Why don't you define a true class and provide an appropriate constructor?

When you get a "private" instance field, make sure you provide the this. scope.

 class Person { constructor(age, drive) { this._age = age this._drive = drive } get age() { return this._age } set age(age) { this._age = age } get drive() { return this._drive } set drive(drive) { this._drive = drive } toString() { return `Person[age=${this.age},drive=${this.drive}]` } get [Symbol.toStringTag]() { return 'Person' } } const person = new Person(18, true) console.log(person) console.log(person.toString()) console.log(Object.prototype.toString.call(person)) console.log(`age: ${person.age}`) console.log(`drive: ${person.drive}`)
 .as-console-wrapper { top: 0; max-height: 100%;important; }

If you want define getters and setters for simple object, you need to use Object.defineProperty()

Read the docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

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