Как мы можем предотвратить опасное поведение в коде ниже?Наследование javascript опасно
var ee = require('events').EventEmitter;
var util = require("util");
util.inherits(strr, ee);
function strr() {
ee.call(this);
this._events = 0; // modify the private member value in parent
}
Если вы не осведомлен this._events является частного переменного члена в родительском объекте EventEmitter, то внутренний данные подрывается (мутировавшим) сами (наследующий класс). Но мы не можем знать все о родительском частном члене.
Приведенный выше код использует node.js и не так просто понять проблему. добавить еще немного
Он будет выводить
Is child an instance of Child? true
Is child an instance of Parent? true
run
Show my secret -> 0
Но если вы случайно имя члена _secre ребенка с _secret, то вы не получите «выход запуска»
function Parent() {
this.x = 0;
this.y = 0;
this._secre = 1;
}
Parent.prototype.run = function(x, y) {
if (this._secre) {
console.log('run');
}
};
function Child() {
Parent.call(this); // call super constructor.
this._secre = 0; //accidently make the same member name with the parent
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.show = function() {
this.run();
console.log("Show my secret -> %s", this._secre);
};
var child = new Child();
console.log('Is child an instance of Child? ' + (child instanceof Child)); // true
console.log('Is child an instance of Parent? ' + (child instanceof Parent)); // true
child.show();
очень опасно, что я не мог понять вопрос ... –
_Cough cough_. Частный член? –