gpt4 book ai didi

javascript - 可以从函数原型(prototype)访问私有(private)构造函数范围的变量吗?

转载 作者:数据小太阳 更新时间:2023-10-29 04:15:08 25 4
gpt4 key购买 nike

根据我对 javascript 的理解,原型(prototype)方法不能访问构造函数范围内私有(private)的变量,

 var Foo = function() {
var myprivate = 'I am private';
this.mypublic = 'I am public';
}

Foo.prototype = {
alertPublic: function() { alert(this.mypublic); } // will work
alertPrivate: function() { alert(myprivate); } // won't work
}

这很有道理,但有没有什么安全且好的方法可以解决这个问题?由于使用原型(prototype)提供了性能优势,因为成员函数只分配一次,所以我想实现类似的功能,同时仍然能够访问我的私有(private)变量。我不认为它会通过使用原型(prototype)来工作,但是是否有另一种模式,例如工厂方法或闭包方法?类似的东西,

var fooFactory = function() {
var _alertPrivate = function(p) { alert(p); } // bulk of the logic goes here
return function(args) {
var foo = {};
var myprivate = args.someVar;
foo.mypublic = args.someOtherVar;
foo.alertPrivate = function() { _alertPrivate(myprivate); };
return foo;
};
}

var makeFoo = new fooFactory();
var foo = makeFoo(args);

我不确定每次创建新 Foo 时是否创建了 _alertPrivate 的新副本,或者是否有任何潜在的性能优势。目的是获得类似于原型(prototype)的功能(因为它可以节省内存),同时仍然能够访问私有(private)变量。

谢谢。

最佳答案

我想出了以下模式来解决这个问题,至少现在是这样。我需要的是一个特权 setter ,以便可以从某些原型(prototype)函数内部更改私有(private)变量,但不能从其他任何地方更改:

 var Foo = (function() {

// the bulk of the objects behavior goes here and is created once
var functions = {
update: function(a) {
a['privateVar'] = "Private variable set from the prototype";
}
};

// the objects prototype, also created once
var proto = {
Update: function() {
this.caller('update');
}
};

// special function to get private vars into scope
var hoist = function(accessor) {
return function(key) {
return functions[key](accessor());
}
}

// the constructor itself
var foo = function foo() {
var state = {
privateVar: "Private variable set in constructor",
// put more private vars here
}
this.caller = hoist(function(){
return state;
});
}

// assign the prototype
foo.prototype = proto;

// return the constructor
return foo;

})();

基本上,一个指向对象内部状态的指针通过一个简单访问器上的闭包被提升到它的原型(prototype) function() { return state; }.在任何给定实例上使用“调用者”函数允许您调用仅创建一次但仍可以引用该实例中保存的私有(private)状态的函数。同样重要的是要注意,原型(prototype)之外的任何函数都不能访问特权访问器,因为“调用者”只接受一个键,该键引用回范围内的预定义函数。

以下是此方法的一些基准,以了解它与纯原型(prototype)制作的比较。这些数字表示在一个循环中创建对象的 80,000 个实例(注意用于基准测试的对象比上面的对象更复杂,这只是为了简化目的):

Chrome :

仅关闭 - 2172 毫秒

原型(prototype)制作(上述方式)- 822 毫秒

原型(prototype)制作(标准方式)- 751 毫秒

火狐:

仅关闭 - 1528 毫秒

原型(prototype)制作(上述方式)- 971 毫秒

原型(prototype)制作(标准方式)- 752ms

如您所见,该方法几乎与普通原型(prototype)制作一样快,而且绝对比仅使用将函数与实例一起复制的普通闭包更快。

关于javascript - 可以从函数原型(prototype)访问私有(private)构造函数范围的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7788175/

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