Search code examples
javascriptoopencapsulationgetter-setter

Declare getter/setter in inheritance class in Javascript


I am familiar with strongly typed OOP language such as C# and Java, so I am a little confused with Javascript. I want my class to be encapsulated, for example:

function Human() {
    var _name = '';
    var _nameChangeCounter = 0;
}

Human.constructor = Human;
Human.prototype = Object.create(Animal);

As you can see, Human extends the Animal class. Now I need a getter and setter for Name, and a getter for NameChangeCounter. In the setter of Name, it should increase the NameChangeCounter. I looked up how to make getter and setter in Javascript in this question:

Name.prototype = {
    get fullName() {
        return this.first + " " + this.last;
    },

    set fullName(name) {
        var names = name.split(" ");
        this.first = names[0];
        this.last = names[1];
    }
};

However, now that prototype is taken for inheritance, how can I do it? Do I have to do the Java-style (create getName, setName, getNameChangeCounter functions)? How do properties like window.location.href implemented?


Solution

  • Found this function on mdn: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Summary

    Here is an example fiddle: http://jsfiddle.net/EfyCX/1/

    And here is some javascript for getters and setters using Object.defineProperties

    Object.defineProperties(Person.prototype, {
        "name": {
            get: function() { return this._name },
            set: function(name) { 
                this.changeCount++
                this._name = name
            }
        }
    })