Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 694
Luke Vo Avatar asked Nov 02 '22 00:11

Luke Vo


1 Answers

This works for me:

function Name(){
    this.first = '';
    this.last = '';
}

Name.prototype.getFullName = function() {
    return this.first + ' ' + this.last;
}

Name.prototype.setFullName = function(fullName){
    var names = fullName.split(" ");
    this.first = names[0];
    this.last = names[1];
}


function Human() {
    var name = new Name(), 
        counter = 0;
    Object.defineProperty(this, 'name', {
        configurable: true,
        enumerable: true,
        get: function(){
            return name;
        },
        set: function(fullName){
            name.setFullName(fullName);
        }
    });
    Object.defineProperty(this, 'counter', {
        configurable:true,
        enumerable: true,
        get: function(){
            return counter;
        },
        set: function(value){
            counter = value;
        }
    });
}

var luke = new Human();
luke.name = 'Luke Skywalker';

console.log(luke.name.first); //Luke
console.log(luke.name.last); //Skywalker
console.log(luke.name.getFullName()); //Luke Skywalker
console.log(luke.name); //Object

luke.name = 'Peter Parker';
console.log(luke.name.first); //Peter
console.log(luke.name.last); //Parker
console.log(luke.name.getFullName()); //Peter Parker
like image 103
Edwin Dalorzo Avatar answered Nov 12 '22 12:11

Edwin Dalorzo