用JavaScript创建setter

时间:2018-07-25 15:03:03

标签: javascript

我想在JS中创建一个setter。但是我的代码有问题,这是我的代码:

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

为什么在此示例中控制台未定义?如何使其正常工作?

2 个答案:

答案 0 :(得分:4)

您的设置员需要将值存储在某个地方;您还需要一个吸气剂才能从那个地方获得价值。

这是一个将值存储在另一个属性中的简单示例:

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

当然,如果要执行此操作,那么使用二传手就没有多大意义了,但这有点超出了这个问题了……


注意:我将您的班级名称更改为Test(而不是test)。 JavaScript中的压倒性约定是,类名(实际上是构造函数名称)最初是大写的。

答案 1 :(得分:1)

尝试以下方法:

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
 }
}