[英]Initializing singleton javascript objects using the new operator?
In javascript, what is the difference between: 在javascript中,有什么区别:
var singleton = function(){ ... }
and 和
var singleton = new function(){ ... }
? ?
Declaring priviliged functions as described by crockford ( http://www.crockford.com/javascript/private.html ) only works using the latter. 如crockford( http://www.crockford.com/javascript/private.html )所述,声明特权函数只能使用后者。
The difference is mainly that in your second example, you are using the Function Expression as a Constructor , the new
operator will cause the function to be automatically executed, and the this
value inside that function will refer to a newly created object. 区别主要在于,在第二个示例中,您将函数表达式用作构造函数 ,
new
运算符将使函数自动执行,并且函数内部的this
值将引用新创建的对象。
If you don't return anything (or you don't return a non-primitive value) from that function, the this
value will be returned and assigned to your singleton
variable. 如果您不从该函数返回任何内容(或不返回非原始值),则
this
值将被返回并分配给您的singleton
变量。
Privileged methods can also be used in your second example, a common pattern is use an immediately invoked function expression , creating a closure where the private members are accessible, then you can return an object that contains your public API , eg: 特权方法也可以在第二个示例中使用,常见的模式是使用立即调用的函数表达式 ,创建一个可以访问私有成员的闭包 ,然后您可以返回一个包含公共API的对象,例如:
var singleton = (function () {
var privateVar = 1;
function privateMethod () {/*...*/}
return { // public API
publicMethod: function () {
// private members are available here
}
};
})();
I think that a privileged function as described by crockford would look like this: 我认为crockford描述的特权函数如下所示:
function Test() {
this.privileged = function() {
alert('apple');
}
function anonymous() {
alert('hello');
}
anonymous();
}
t = new Test; // hello
t.privileged(); // apple
// unlike the anonymous function, the privileged function can be accessed and
// modified after its declaration
t.privileged = function() {
alert('orange');
}
t.privileged(); // orange
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.