Javascript Object Define Getters And Setters

Description

Javascript Object Define Getters And Setters



function Person( nameStr ) {
    let name = nameStr;
    //from   w ww. jav a 2 s  .c om
    this.__defineGetter__("name", function() {
        return name;
    });

    this.__defineSetter__("name", function(nameStr) {
        name = nameStr;
    });
}

Person.prototype = {
    get name() {
        return this._name;
    },
    set name(nameStr) {
        this._name = nameStr;
    }
}

let dave = new Person("Dave");

console.log(dave.name);

dave.name = "new name";
console.log(dave.name);

console.log("Getter for name: " + dave.__lookupGetter__("name").toString() );



PreviousNext

Related