在传统的OOP语言中,我们通常使用私有/公共来实现数据封装。
在Javascript中,不再有私有或公共;有人告诉我;通过使用闭包,可以实现数据封装。我想知道是怎么回事,背后的逻辑是什么?
发布于 2015-04-05 17:04:23
您可以通过这种方式将数据封装在“类”(在JavaScript 6之前没有真正的类)中
var yourClass = function() {
var privateProp = 'sometext'; //private prop
this.prop = 1; //public
this.getPrivateProp = function() {
return privateProp; //access to your private prop with a closure
}
}
var test = new yourClass();
//when you use 'new', everything in 'this' is returned in your object.
//'privateProp' is not in 'this' but 'getPrivateProp' is.
//You got your private data not directly accessible from outside.
test.prop; // 1
test.privateProp;//undefined
test.getPrivateProp();// 'sometext'发布于 2015-04-05 17:04:11
实际上并没有创建真正的私有成员。
检查以下代码:
function A() {
var doStuff1 = function() { };
this.doStuff2 = function() {
doStuff1();
};
};
var instance = new A();
instance.doStuff2();因为doStuff2被声明并添加到this中,所以它是A实例的一部分,而doStuff1被声明为构造函数中的局部变量,因此,只能在同一构造函数中使用闭包来访问它。
顺便说一句,我不喜欢这个模式,因为当你不使用原型继承时,它工作得很好。
假设我想使用原型:
function A() {
var doStuff1 = function() {}; // ??????
};
A.prototype = {
doStuff2: function() {
// How do I access a local variable defined
// in the constructor function local scope?
}
};因此,整个模式适用于您不想使用原型继承的简单场景。
此外,这种模式在您想要使用Object.create(...)的场景中也不起作用,因为根本没有构造函数...
// Constructor isn't ever called...
var instance = Object.create(A.prototype);那么,如何在JavaScript中实现这种封装呢?目前还不可能,但许多库和框架已经选择使用命名约定,让开发人员知道库/框架代码使用了什么,以及打算在实际的第三方开发中使用什么。
例如:
function A() {
};
A.prototype = {
___doStuff1___: function() {},
doStuff2: function() {
this.___doStuff1___();
}
};毕竟,这是一个命名约定,其中被___排序的成员被认为是私有的,或者不是为第三方开发人员准备的。
其他库/框架使用$$ (f.e.Angular,$$privateMember)。
https://stackoverflow.com/questions/29455692
复制相似问题