Getters and Setters in a function (javascript)

后端 未结 3 577
悲&欢浪女
悲&欢浪女 2021-01-12 16:08

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

var people = {
  name: \"Alex\",
  get say         


        
3条回答
  •  不思量自难忘°
    2021-01-12 16:38

    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}!`;
        }
    }
    

提交回复
热议问题