gpt4 book ai didi

javascript继承是危险的

转载 作者:行者123 更新时间:2023-12-03 09:30:11 25 4
gpt4 key购买 nike

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

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 对象中的私有(private)变量成员,那么内部数据就会被您自己破坏(变异) (继承类)。但我们无法了解父私有(private)成员的所有信息。

上面的代码使用了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

但是,如果您不小心将子级的 _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();

最佳答案

不,阻止外部脚本访问“私有(private)”变量的唯一方法是在函数内限制该私有(private)变量的范围:

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

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

obj._private

但实际上没有什么可以阻止其他开发人员访问此类属性(如果他们有权访问其父对象)并可能更改其值。

关于javascript继承是危险的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31538260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com