Pac*_*ier 6 javascript function ecmascript-5
我有这段代码:
var Human=function(name){
this._name=name;
};
Human.prototype.Shout=function(){
alert(this._name);
};
var tom=new Human("tom");
var john=new Human("john");
alert(tom.Shout===john.Shout);
Run Code Online (Sandbox Code Playgroud)
现在._name不是"私人".我想使._name"私有",但同时我不希望为每个人类实例创建额外的函数(换句话说,tom.Shout必须是===到john.Shout)因为创建了附加函数每个实例都很好..不必要(ok offtopic - 我们可以在另一个线程上讨论这个)
我的结论是,我想要实现的目标(将._name设为"私有"并且同时拥有tom.Shout===john.Shout)是不可能的.
但在得出任何结论之前,我只想200%肯定.
(只要符合要求,我欢迎任何黑客攻击,即不为每个实例创建额外的功能)
如果我们必须创建其他函数来进行范围确定,那么该数字应该是固定数字,并且该数字不应随着每个额外的Human实例而增加.
更新
您寻找的@name是实例变量。祈祷它在 es.next 中,但我们还没有。也许两年后。
如果您关心干净的 API,那么这里是您的解决方案:
function Class(foo) {
Class.priv(this).foo = foo;
}
Class.priv = (function() {
var cache = [],
uid = 1;
return function(obj) {
if (!this.__id) {
this.__id = uid;
cache[uid++] = {};
}
return cache[this.__id];
};
}());
Class.prototype.bar = function() {
console.log(Class.priv(this).foo);
}
Run Code Online (Sandbox Code Playgroud)
将所有数据存储在缓存中作为构造函数的函数。对象上没有杂乱的数据。
原来的
然而,不存在“私人”这样的东西。
您所能做的就是在函数内创建一个局部变量。
构造函数
var Human = function(name) {
// local variable.
var _name = name;
}
Run Code Online (Sandbox Code Playgroud)
有一个局部变量,根据局部定义,该变量在构造函数之外不可使用。
这意味着您无法像原型一样通过外部代码访问它。
但是你可以做的是使用 ES5 将其设置为只读
var Human = function(name) {
Object.defineProperty(this, "name", { value: name });
}
Run Code Online (Sandbox Code Playgroud)
如果你能真正实现你的要求,你就会在 js 方面取得巨大的突破。我已经尝试这样做了好几个小时。
不同的模式是:
var Human = function(name) {
this.name = name;
return {
Shout: this.Shout.bind(this)
};
}
Human.prototype.Shout = function() {
console.log(this.name);
}
Run Code Online (Sandbox Code Playgroud)
不过,这会产生为每个实例调用.bind和创建新对象的开销。
| 归档时间: |
|
| 查看次数: |
178 次 |
| 最近记录: |