在Javascript中的继承类中声明getter/setter

Luk*_* Vo 5 javascript oop encapsulation getter-setter

我熟悉强类型的OOP语言,如C#和Java,所以我对Javascript有点困惑.我希望我class被封装,例如:

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

Human.constructor = Human;
Human.prototype = Object.create(Animal);
Run Code Online (Sandbox Code Playgroud)

如您所见,Human扩展了Animal类.现在我需要一个吸气剂和吸气剂Name,以及吸气剂NameChangeCounter.在二传手中Name,它应该增加NameChangeCounter.我在这个问题中查找了如何在Javascript中制作getter和setter :

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

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

但是,现在原型被用于继承,我该怎么办呢?我必须做的Java风格(创建getName,setName,getNameChangeCounter功能)?物业如何window.location.href实施?

bot*_*ens 1

在mdn上找到这个函数: https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Summary

这是一个小提琴示例: http: //jsfiddle.net/EfyCX/1/

这里是一些使用 Object.defineProperties 的 getter 和 setter 的 javascript

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