Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters and Setters in a function (javascript)

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);
like image 342
Alexey Tseitlin Avatar asked Jul 14 '16 06:07

Alexey Tseitlin


2 Answers

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}!`;
    }
}
like image 128
Chiru Avatar answered Oct 17 '22 20:10

Chiru


For the case you want to define a property like as name for a function with more control, we can use Object.defineProperty on function itself as following:

function people(name) {

    //this.name = name; //this can be modified freely by caller code! we don't have any control

    var _name = name; //use a private var to store input `name`
    Object.defineProperty(this, 'name', {
        get: function() { return _name; },  //we can also use `return name;` if we don't use `name` input param for other purposes in our code
        writable: false, //if we need it to be read-only
        //... other configs
    });

};

var person = new people('Alex');
console.log(person.name); //writes Alex
like image 40
S.Serpooshan Avatar answered Oct 17 '22 22:10

S.Serpooshan