Javascript继承是危险的

javascript inherit is dangerous

本文关键字:危险 继承 Javascript      更新时间:2023-09-26

我们如何防止下面代码中的危险行为?

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
}

如果你不知道这一点。_events是父EventEmitter对象中的私有变量成员,然后内部数据被您自己(继承类)破坏(突变)。但是我们不可能知道父类私有成员的所有信息。

上面的代码使用node.js和不那么容易理解的问题。我添加了一些

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._secret = 0; //accidently make the same member name with the parent
}
// subclass extends superclass
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.show = function() {
  this.run();
  console.log("Show my secret -> %s", this._secret);
};
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(); 

输出

Is child an instance of Child? true
Is child an instance of Parent? true
run
Show my secret -> 0

但是如果您不小心将子节点的_secret成员命名为_secret,那么您将不会得到"run output"

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(); 

不,阻止外部脚本访问"私有"变量的唯一方法是将该私有变量限定在函数内:

;(function() {
    var private_var;
)());

如果对象的属性打算在对象内部使用,但不打算在对象外部访问,则习惯使用下划线前缀命名约定。

obj._private

但是实际上没有什么可以阻止另一个开发人员访问这样的属性(如果他们可以访问它的父对象),并且可能改变它的值。

有更好的方法来继承EventEmitter

Child.prototype.__proto__ = EventEmitter.prototype;
Child.prototype = Object.create(EventEmitter.prototype)

如果你不知道这一点。_events是父EventEmitter对象中的私有变量成员,

不,这不是私人的。如果你不相信,去看看EventEmitter的源代码。

也就是说,EventEmitter是一个关于如何在JavaScript中管理状态的有趣例子,值得研究。

我们还能说什么?JavaScript不是Java。: p