You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
SomeClass.prototype._somePrivateMethod = function () {
// TODO
};
但是老道发话了(引用原话):
Do not use _ (underbar) as the first character of a name. It is sometimes used to indicate privacy, but it does not actually provide privacy. If privacy is important, use the forms that provide private members. Avoid conventions that demonstrate a lack of competence.
和私有方法类似,下例是一个加_的特权属性:
function Car() {
this._mile = 0;
}
Car.prototype.getMile = function () {
return this._mile;
};
但很遗憾,依然无法实现真正的私有,我们可以简单地: var car = new Car(); car._mile = 1;
改进1.0版
var Car = (function () {
var privateStore = {};
var uid = 0;
function Car() {
privateStore[this.id = uid++] = {};
privateStore[this.id].mile = 0;
}
Car.prototype.getMile = function () {
return privateStore[this.id].mile;
};
}());
JS之私有
Jefferson其实蛮早就研究过了这个topic并写了sample。今天只不过整理出文字来而已。
一般说来,如果想原型中实现私有方法,我们约定俗成地加一个_:
但是老道发话了(引用原话):
Do not use _ (underbar) as the first character of a name. It is sometimes used to indicate privacy, but it does not actually provide privacy. If privacy is important, use the forms that provide private members. Avoid conventions that demonstrate a lack of competence.
和私有方法类似,下例是一个加_的特权属性:
但很遗憾,依然无法实现真正的私有,我们可以简单地: var car = new Car(); car._mile = 1;
改进1.0版
用uid生成递增的Car的this.id,所有的setter和getter都通过privateStore,这样无法直接写car.mile = 1了。实现了私有保护!
貌似有用诶~不过这是终极方案了吗?No,原因如下:
1 额外代码茫茫多,业务一旦复杂了,FE还要写一堆privateStore神马的,会精神崩溃直至跳楼;
2 this.id被占用,如果某个业务类也需要this.id,就傻眼了;
3 内存泄露——privateStore会对每个实例有引用,这些实例不会被回收。
改进思路
1 声明私有的途径,好歹应该快捷方便些;
2 私有方法可以调用共有方法;
3 不能占用this.id;不能有内存泄露问题。
改进2.0版
设计一个util函数,PrivateParts.create。传入privateMethods,其中:
var privateMethods = Object.create(A.prototype); // A为类名
而var _ = PrivateParts.create(privateMethods);
之后所有的私有变量、私有方法,都通过:_(this).*** 来获取句柄。
End
上述依然远非最终版本,只是自己设计的一个2.0版本而已。
司徒正美的《JS框架设计》里面chapter5也有很多不错的类工厂范例,值得推荐!
So, 欢迎大家提出建议,Jefferson Deng waiting for you.
The text was updated successfully, but these errors were encountered: