现在我努力搜索以完成此任务:具有完全封装且无需“新”实例化它的完美类。经过一段时间的搜索,我想出了这个:
function Test(x){
var innerFunction = function(y){
var variable = y;
this.getA = function(){
return variable;
}
this.setA = function(x){
variable = x;
}
}
return new innerFunction(x);
}
但测试结果证明是错误的:
var a = Test("foo");
var b = Test("baz");
alert(a.constructor == b.constructor); //false, not good!
alert(a.constructor.name == b.constructor.name); //true
所以似乎有错误的范围,所以我使用了一个公共内部函数:
function Test(x){
function innerFunction(y){
var variable = y;
this.getA = function(){
return variable;
}
this.setA = function(x){
variable = x;
}
}
return new innerFunction(x);
}
并且运行一些广泛的测试证明它是正确的:
var a = Test("foo");
var b = Test("baz");
alert(a.constructor == b.constructor); //true, made it!
alert(a.constructor.name == b.constructor.name); //true
alert(a.getA()); //"foo" as expected
alert(a.getA() == b.getA()); //false as expected
a.variable = "whatever";
alert(a.getA()); //"foo" as expected
alert(a.variable); //"whatever", doesn't seem preventable
a.setA("somewhere");
alert(a.getA()); //"somewhere", as expected
alert(a.variable); //"whatever", doesn't seem preventable
但是,我们可以这样使用几个函数吗?这是我的第一种方法:
function Test(x){
function innerFunction(y){
var variable = y;
this.getA = function(){
return variable;
}
this.setA = function(x){
variable = x;
}
}
return new innerFunction(x);
}
function TestToo(x){
function innerFunction(y){
var variable = y;
this.getA = function(){
return variable;
}
this.setA = function(x){
variable = x;
}
}
return new innerFunction(x);
}
var a = Test("foo");
var b = Test("baz");
var c = TestToo("foo");
var d = TestToo("baz");
alert(a.constructor == b.constructor); //true, as expected
alert(a.constructor.name == b.constructor.name); //true, as expected
alert(c.constructor == d.constructor); //true, as expected
alert(c.constructor.name == d.constructor.name); //true, as expected
alert(a.constructor == c.constructor); //false, as expected
alert(a.constructor.name == c.constructor.name); //true, as NOT expected
所以这是它?我们真的总是需要知道a.constructor.name
与字符串比较的内部类结构吗?不,因为在 Javascript 中你可以做任何事情(你只需要知道如何做,而不是为什么),我找到了这个最终解决方案:
function Test(x){
function Test(y){
var variable = y;
this.getA = function(){
return variable;
}
this.setA = function(x){
variable = x;
}
}
return new Test(x);
}
function TestToo(x){
function TestToo(y){
var variable = y;
this.getA = function(){
return variable;
}
this.setA = function(x){
variable = x;
}
}
return new TestToo(x);
}
var a = Test("foo");
var b = Test("baz");
var c = TestToo("foo");
var d = TestToo("baz");
alert(a.constructor == b.constructor); //true, as expected
alert(a.constructor.name == b.constructor.name); //true, as expected
alert(c.constructor == d.constructor); //true, as expected
alert(c.constructor.name == d.constructor.name); //true, as expected
alert(a.constructor == c.constructor); //false, as expected
alert(a.constructor.name == c.constructor.name); //false, q.e.d.!
我是认真的,我不知道为什么会这样。但它确实 100% 有效,具有 100% 的对象封装,以及与 Java 类的 1:1 相等性。;-)