所以我一直在研究完全开发面向对象的JavaScript实践,并想知道以下示例.
据我所知,(对我而言)下面的"秘密"字段是"私有的":
var MyObject = function() {
var secret = 'sshhh';
this.getSecret() = function() {
return secret;
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为字段秘密具有内部功能可以访问的功能范围,但是外部没有任何东西......到目前为止这么好.
但我已经看到了以下内容(特别是在Douglas Crockford的书中):
var MyObject = function() {
var secret = 'sshhh';
return {
getSecret : function() {
return secret;
}
}
}();
Run Code Online (Sandbox Code Playgroud)
并且想知道差异是什么,为什么它更好?我知道在这种情况下,我们甚至没有返回私有字段所在的同一个对象,但由于无法直接访问该字段,因此看不到很大的好处.
这些例子非常不同......第一个创建了一个"MyObject" function,当使用构造函数调用时new,它将具有"getSecret" function作为属性; 第二个创建一个"MyObject" Object,其中"getSecret" function作为属性.
在这方面,这有点像静态方法和公共方法之间的区别.在第一种情况下,该方法仅在调用构造函数时存在,而不是在构造函数本身中存在.在第二种情况下,没有构造函数.
所以,假设你有:
var MyObject1 = function() {
var secret = 'sshhh';
this.getSecret = function() {
return secret;
}
}
// ...
var MyObject2 = function() {
var secret = 'sshhh';
return {
getSecret : function() {
return secret;
}
}
}();
Run Code Online (Sandbox Code Playgroud)
运行一些测试:
MyObject1.getSecret();
// TypeError: Object has no method 'getSecret'
var m1 = new MyObject1();
m1.getSecret();
// "sshhh"
MyObject2.getSecret();
// "sshhh"
var m2 = new MyObject2();
// TypeError: object is not a function
Run Code Online (Sandbox Code Playgroud)
所以MyObject1就像一个类,而MyObject2就像一个静态类.
| 归档时间: |
|
| 查看次数: |
702 次 |
| 最近记录: |