Javascript新对象(函数)与内联调用 [英] Javascript new object (function ) vs inline invocation

查看:142
本文介绍了Javascript新对象(函数)与内联调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var object = new function是否有任何注意事项来确定哪个更适合用私人成员创建对象? (){
var private =private variable;
return {
method:function(){
..dosomething with private;
}
}
}

VS

  var object = function(){
...
}();

基本上在这里使用NEW有什么区别,并且在我们定义之后立即调用函数? new 运算符使得函数被调用,如 href =https://developer.mozilla.org/zh/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_a_Constructor_Function =noreferrer>构造函数。



new 的用途

code>运算符是在构造函数中创建一个对象( this value),设置正确的 [[Prototype]] 内部属性,构建原型链并实现继承(您可以在 [[Construct]] 操作)。

<我会建议你留下来嵌入式调用模式。


Is there any considerations to determine which is better practice for creating an object with private members?

var object = new function () { 
   var private = "private variable";
   return {
       method : function () { 
           ..dosomething with private;
       }
   }
}

VS

var object = function () {
 ...
}();

Basically what is the difference between using NEW here, and just invoking the function immediately after we define it?

解决方案

The new operator causes the function to be invoked like a Constructor Function.

I've seen that pattern before, but I don't see any benefits of using it.

The purpose of the new operator is to create an object (the this value inside the constructor), setting the right [[Prototype]] internal property, to build the prototype chain and implement inheritance (you can see the details in the [[Construct]] operation).

I would recommend you to stay with the inline invocation pattern.

这篇关于Javascript新对象(函数)与内联调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆