函数中的getter和Setter(javascript)

Ale*_*lin 5 javascript function getter-setter

在像这样的对象中使用"get"时,"get"起作用:

var people = {
  name: "Alex",
  get sayHi() {
    return `Hi, ${this.name}!`
    }
};

var person = people;

document.write(person.sayHi);
Run Code Online (Sandbox Code Playgroud)

但是使用函数我会收到错误.如何在这样的函数中使用Getters和Setter?

function People2() {
  this.name = "Mike";
  get sayHi() {
    return `Hi, ${this.name}!`;
  }
};

var user = new People2();

document.write(user.sayHi);
Run Code Online (Sandbox Code Playgroud)

Chi*_*iru 8

您只能在类(ES2015)和对象文字中使用实际getset关键字.

ECMAScript 5

在ES5中,您通常会使用Obect.defineProperty来实现您要实现的目标:

function People2() {
    this.name = "Mike";
}
Object.defineProperty(People2.prototype, "sayHi", {
    get: function() {
        return "Hi, " + this.name + "!";
    }
});
Run Code Online (Sandbox Code Playgroud)

ECMAScript 2015

在ES2015中,您还可以使用类来实现所需的行为:

class People2 {
    constructor() {
        this.name = "Mike";
    }
    get sayHi() {
        return `Hi, ${this.name}!`;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以试试这个

<script>
function People2(name) {
  this.name = name;  
};

People2.prototype = {
  get sayHi() {
    return `Hi, ${this.name}!`;}
};

var user = new People2('Alex');

document.write(user.sayHi);
</script>
Run Code Online (Sandbox Code Playgroud)

或者这个...

<script>
function people(name) {
    this.name = name;
};

Object.defineProperty(people.prototype, 'sayHi', {
    get: function() { return `Hi, ${this.name}!`; }
});

var person = new people('Alex');

document.write(person.sayHi);
</script>
Run Code Online (Sandbox Code Playgroud)