Getters and Setters in a function (javascript)

你离开我真会死。 提交于 2019-12-01 04:06:52

问题


When using get in an object like this, get works:

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

var person = people;

document.write(person.sayHi);

But with a function I get an error. How to use Getters and Setters in a function like this?

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

var user = new People2();

document.write(user.sayHi);

回答1:


You can use the actual get and set keywords only in classes (ES2015) and object literals.

ECMAScript 5

In ES5, your would typically use Object.defineProperty to implement what you're trying to achieve:

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

ECMAScript 2015

In ES2015, you could also use classes to achieve the desired behavior:

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



回答2:


You can try this

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

or this one...

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



回答3:


For example, use this:

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


来源:https://stackoverflow.com/questions/38367348/getters-and-setters-in-a-function-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!