Javascript继承是危险的
javascript inherit is dangerous
我们如何防止下面代码中的危险行为?
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
相关文章:
- 从控制器继承了隔离的作用域以生成可重用的指令
- 两个指令创建新的继承的和隔离的作用域-元素得到哪个
- 当使用控制器作为语法时,如何从父指令继承属性
- 以jquery方式继承Javascript
- JavaScript对象不是从原型链继承的
- 使用Object.create()的角度服务继承
- 数据与Javascript中的继承冲突
- JavaScript对象继承问题
- Javascript嵌套函数属性继承
- 为什么不't htmlCollection从数组继承
- 继承的属性检查
- 没有预定义宽度的固定元素最初放在引导容器中,不会从父元素继承宽度
- 如何使用原型继承编写一个整洁灵活的复杂javascript应用程序
- 使用技巧在javascript中强制执行私有继承
- $emit,$broadcast,原型继承
- 如何检查DOM节点是否继承自构造函数
- Javascript多重继承模式
- 玉中继承模板的修改
- Angular中的作用域继承$broadcast
- Javascript继承是危险的