Javascript创建对象 - 多种方法,任何差异? [英] Javascript creating objects - multiple approaches, any differences?
问题描述
我已经看到了一些在javascript中实例化对象的不同方法,想知道各种方法的优点/缺点以及为什么要使用其中一种方法。
I have seen a few different ways to instantiate objects in javascript, wanted to know the benefits/drawbacks of the various approaches and why you would use one over the other.
方法1
var obj = {
prop: value,
.
.
.
}
方法一是标准方法,没什么新东西:)
Approach one is standard approach, nothing new :)
方法2
var obj = new function() {
var prop1 = value1;
var fn1 = function() {
};
.
.
.
this.prop2 = value2;
.
.
.
}();
函数方法,我想将此方法与方法3进行比较。函数方法主要用于封装(正确吗?)
The function approach, I wanted to compare this approach with approach 3. The function approach is primarily used for encapsulation (correct?)
方法3
var obj = (function() {
var prop1 = value1;
var fn1 = function() {
};
.
.
.
return {
prop2: value2,
.
.
.
}
})();
通过这种方法,我不太清楚其使用背后的原因。它与方法2有何不同?两者都可以用来封装逻辑。
With this approach, I do not quite see the reasoning behind its usage. How does it differ from approach 2? Both can be used to encapsulate logic.
这样我们可以传递参数,所以我们可以处理任何潜在的冲突吗?例如jquery的 $
语法 - 但您也可以使用方法2 ...
Is it so we can pass in parameters, so we can deal with any potential conflicts?? E.g jquery's $
syntax - but you can also do this with approach 2...
谢谢。
编辑:
我知道方法1和3是相似的(因为它们都返回对象)但是方法3也创建了一个闭包。哪种方法2也有。
I am aware the approach 1 and 3 are similar (in that they both return objects) however approach 3 also creates a closure. Which approach 2 also does.
这是我问题的基础,2和3都创建了闭包,但它们之间有什么区别。
That is the basis of my question really, both 2 and 3 create closures, but what is the difference between them.
推荐答案
在方法#2和#3中,结果对象的构造函数
属性将不同。
In approaches #2 and #3 the constructor
property of the resulting objects will be different.
实际上,这意味着第二种方法允许您使用匿名构造函数实例化多个对象:
In practice it means that the second approach allows you to instantiate more than one object using the anonymous constructor function:
x = new function() { alert(1) };
y = new x.constructor; // shows the message too
模块模式与匿名构造函数的实例包括道格拉斯克罗克福德的引用,其中他解释了为什么他认为方法#3优于#2。
The top answer to Module pattern vs. instance of an anonymous constructor includes a quote from Douglas Crockford in which he explains why he thinks the approach #3 is better than #2.
这篇关于Javascript创建对象 - 多种方法,任何差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!