Intereting Posts

覆盖 et的JavaScript对象实例(与原型?)的最佳方法?

示例代码我如何希望实例工作:

var brother = new Person("James"); console.log(brother.status); // "James, current location: home, health condition: saber" brother.status = { location: "pub", "health condition": "drunk as a skunk" }; console.log(brother.status); // "James, current location: pub, health condition: drunk as a skunk" 

问题是如何编程对象Person,其原型以及如何使用Object.defineProperty来实现这个(或类似的)行为最优雅的方式。

到目前为止,我做了一些解决scheme,但是我不想在这里解释它来打扰你的想法。

关键的答案应该包含对象与方法和属性不复制每个实例和对象必须很容易inheritance。

Solutions Collecting From Web of "覆盖 et的JavaScript对象实例(与原型?)的最佳方法?"

 // Constructor function Person(name){ // In prototype, Can be in herited this._name = name; this._status; // Not available in prototype, hence cannot be inherited age = 20; function incAge(){ age++; } // Available in instances, Privilege. this.getAge = function(){ incAge(); // Accessing private members return age; } } Person.prototype.constructor = Person; Object.defineProperty(Person.prototype, "status", { configurable : true, // If you want it to be changed in derived class enumerable : false, get : function(){ this._status = this._status || {location : "home", "health condition" : "saber"}; return this._name + ", current location: "+ this._status.location+", health condition: "+this._status["health condition"]; }, set : function(status){this._status = status} }); //----DERIVED CLASS--- function SuperPerson(name){ Person.call(this, name); } SuperPerson.prototype = Object.create(Person.prototype); SuperPerson.prototype.constructor = SuperPerson; Object.defineProperty(Person.prototype, "status", { enumerable : false, get : function(){ this._status = this._status || {location : "BatCave", "health condition" : "I dont have parents to take care of me"}; return this._name + ", current location: "+ this._status.location+", health condition: "+this._status["health condition"]; } }); 

如果你有兴趣, 这篇文章精美地解释了Object.defineProperty方法的描述符。

你可以为所有人定义一个通用的私有defaultStatus ,然后为每个人创build一个从defaultStatusinheritance的私有status 。 然后,公开status ,在设置时,将新数据分配给私人status (我使用ES6 Object.assign ,可以填充 )。 获取时,它build立所需的string。

 var Person = (function() { var defaultStatus = { location: 'home', health: 'saber' }; return function Person(name) { var status = Object.create(defaultStatus); Object.defineProperty(this, 'status', { enumerable: true, get: function() { return [ name, "current location: " + status.location, "health condition: " + status.health ].join(', '); }, set: Object.assign.bind(void 0, status) }); }; })();