JavaScript封装 [英] JavaScript Encapsulation
问题描述
所以我一直在研究完全开发面向对象的JavaScript实践,并对以下示例感到疑惑。
So I've been looking into full development object oriented JavaScript practices, and wonder about the following examples.
据我了解,(并且它有意义me)以下'秘密'字段是'私人':
As I understand it, (and it makes sense to me) that the following 'secret' field is 'private' :
var MyObject = function() {
var secret = 'sshhh';
this.getSecret() = function() {
return secret;
}
}
这是因为现场保密具有内部功能可以访问的功能范围,但没有任何外部...到目前为止一切都很好。
and this is because the field secret has function scope that the inner function can access, but nothing outside ... so far so good.
但是我已经看到了以下内容(特别是道格拉斯克罗克福德的书):
But I've seen the following around (and especially in Douglas Crockford's book) :
var MyObject = function() {
var secret = 'sshhh';
return {
getSecret : function() {
return secret;
}
}
}();
并且想知道区别是什么,为什么它更好?据我所知,在这种情况下,我们甚至没有返回私有字段所在的同一个对象,但由于无法直接访问该字段,因此看不到很大的好处。
and was wondering what the difference is, why is it better? I understand that in this case we're not even returning the same object that the private field exists in, but don't see a huge benefit as you can't access the field directly either way.
推荐答案
这些例子非常不同......第一个创建一个MyObject函数
,当被调用时作为使用 new
的构造函数,将具有getSecret函数
作为属性;第二个创建一个MyObject Object
,并将getSecret函数
作为属性。
Those examples are very different... The first creates a "MyObject" function
that, when called as a constructor using new
, will have a "getSecret" function
as a property; the second creates a "MyObject" Object
with a "getSecret" function
as a property.
在这方面,这有点像静态方法和公共方法之间的区别。在第一种情况下,该方法仅在调用构造函数时存在,而不是在构造函数本身中存在。在第二种情况下,没有构造函数。
In that respect, this is sort of like the difference between a static method and a public method. In the first case, the method only exists when the constructor is called, not in the constructor itself. In the second case there is no constructor.
所以假设你有:
var MyObject1 = function() {
var secret = 'sshhh';
this.getSecret = function() {
return secret;
}
}
// ...
var MyObject2 = function() {
var secret = 'sshhh';
return {
getSecret : function() {
return secret;
}
}
}();
运行一些测试:
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
所以MyObject1就像一个类, MyObject2就像一个静态类。
So MyObject1 is like a class, and MyObject2 is like a static class.
这篇关于JavaScript封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!