0

I want to create a setter in JS. But there is something wrong with my code, and this is my code:

class test {
  constructor(str) {
    this.name = str;
  }

  set name(str) {
    this.sayHi();
  }
  sayHi() {
    let temp = this.name;
    console.log(`My name is ${temp}`)
  }
}

let a = new test('bill') //My name is undefined
a.sayHi() //My name is undefined

why does it console undefined in this example?how to make it work?

2
  • 5
    Because you're not setting anything in the setter. Commented Jul 25, 2018 at 15:04
  • console.log('My name is ' + this.name) Commented Jul 25, 2018 at 15:05

2 Answers 2

4

Your setter needs to store the value somewhere; you'll also need a getter to get the value from that place.

Here's a simple example storing the value in another property:

class Test {
    constructor(str) {
        this._name = str;  // ***
        // (You might use `this.name = str` here, setters are sometimes
        // considered an exception to the "don't call methods in the
        // constructor" rule)
    }

    set name(str) {
        this._name = str;  // ***
    }
    
    get name() {           // ***
        return this._name; // ***
    }                      // ***
    
    sayHi() {
        let temp = this.name;
        console.log(`My name is ${temp}`)
    }
}

let a = new Test('bill')   //My name is undefined
a.sayHi()  //My name is undefined

Of course, if you're going to do that, it doesn't make a lot of sense to have a setter, but that's getting a bit afield of the question...


Note: I changed the name of your class to Test (instead of test). The overwhelming convention in JavaScript is that class names (really constructor function names) are initially-capitalized.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your explanation:) i am new for JavaScript,and i don't know how to use setter and getter in the right way,is there any information for this?
thank you for your explanation:) i am new for JavaScript,and i don't know how to use setter and getter in the right way,is there any information for this?
1

Try this instead:

class test {
 constructor(str) {
     this.name = str;
 }

 set name(str) {
     this._name = str
 }
 sayHi() {
     let temp = this.name;
     console.log(`My name is ${temp}`)
 }
 get name() {
     return this._name
 }
}

2 Comments

@Li357 Otherwise you'll get infinite recursion
@dorintufar I didn't see that, my bad

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.