在 JavaScript 中创建新对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2653299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating New Objects in JavaScript
提问by Ken Ray
I'm a relatively newbie to object oriented programming in JavaScript, and I'm unsure of the "best" way to define and use objects in JavaScript. I've seen the "canonical" way to define objects and instantiate a new instance, as shown below.
我是 JavaScript 中面向对象编程的新手,我不确定在 JavaScript 中定义和使用对象的“最佳”方式。我已经看到了定义对象和实例化新实例的“规范”方式,如下所示。
function myObjectType(property1, propterty2) {
this.property1 = property1,
this.property2 = property2
}
// now create a new instance
var myNewvariable = new myObjectType('value for property1', 'value for property2');
But I've seen other ways to create new instances of objects in this manner:
但是我已经看到了以这种方式创建新对象实例的其他方法:
var anotherVariable = new someObjectType({
property1: "Some value for this named property",
property2: "This is the value for property 2"
});
I like how that second way appears - the code is self documenting. But my questions are:
我喜欢第二种方式的出现方式 - 代码是自我记录的。但我的问题是:
Which way is "better"?
Can I use that second way to instantiate a variable of an object type that has been defined using the "classical"way of defining the object type with that implicit constructor?
If I want to create an array of these objects, are there any other considerations?
哪种方式“更好”?
我可以使用第二种方法来实例化一个对象类型的变量,该变量是使用“经典”方式定义的对象类型的隐式构造函数?
如果我想创建这些对象的数组,还有其他考虑吗?
Thanks in advance.
提前致谢。
采纳答案by James
It's really down to taste. This way:
这真的是味道。这边走:
var anotherVariable = new someObjectType({
property1: "Some value for this named property",
property2: "This is the value for property 2"
});
... is generally better if there's more than 2/3 arguments, as it aids readability and makes it easier to avoid the optional argument problem (fn(null,null,null,123')).
... 如果参数超过 2/3,通常会更好,因为它有助于提高可读性并更容易避免可选参数问题 ( fn(null,null,null,123'))。
Another consideration is performance. Passing arguments in the conventional way will be faster, but this speed gain only becomes significant in very performance-sensitive situations.
另一个考虑因素是性能。以传统方式传递参数会更快,但这种速度增益仅在对性能非常敏感的情况下才会变得显着。
Can I use that second way to instantiate a variable of an object type that has been defined using the "classical"way of defining the object type with that implicit constructor?
我可以使用第二种方法来实例化一个对象类型的变量,该变量是使用“经典”方式定义的对象类型的隐式构造函数?
Not easily. If you want to instantiate a constructor by using a hash instead of just passing arguments, and you don't have control over the source, then you could "wrap" it:
不容易。如果您想通过使用散列而不是仅传递参数来实例化构造函数,并且您无法控制源,那么您可以“包装”它:
var _constructor = SomeConstructorFunction;
SomeConstructorFunction = function(hash) {
return new _constructor(hash.property1, hash.property2);
};
I wouldn't really recommend messing with third-party APIs just for the sake of style though.
不过,我真的不建议仅仅为了风格而搞乱第三方 API。
If I want to create an array of these objects, are there any other considerations?
如果我想创建这些对象的数组,还有其他考虑吗?
How big is the array? What's the array for exactly? Performance might be worth considering...
阵列有多大?数组到底是干什么用的?性能可能值得考虑......
回答by Matt Briggs
Best way to create javascript objects is quit using new (at least if you subscribe to the crockford camp)
创建 javascript 对象的最佳方法是使用 new 退出(至少如果您订阅了 crockford 阵营)
myObjectType = function(props) {
// anything defined on props will be private due to the closure
props.privateVar = "private";
// anything defined on obj will be public
obj = {};
obj.testing = new function() {
alert(props.privateVar);
};
return obj;
};
instance = myObjectType({prop1: "prop"});
// if we want inheritance, it just means starting with the base type instead of
// a new object
subType = function(props) {
obj = myObjectType(props);
obj.subTypeProperty = "hello.";
return obj;
};
Page 52 of Javascript: The Good Parts, I highly recommend it :-)
Javascript: The Good Parts 的第 52 页,我强烈推荐它:-)
回答by Nick Craver
1) I would say method #2 is much preferred, for me anyway. The example with 2 properties is not that different, but what if you wanted to do this:
1)我会说方法#2是更受欢迎的,无论如何对我来说。具有 2 个属性的示例并没有什么不同,但是如果您想这样做,该怎么办:
var anotherVariable = new someObjectType({
property1: "Some value for this named property",
property2: "This is the value for property 2"
//Leaving several properties out, don't want them populated
property8: "This is the value for property 8"
property9: "This is the value for property 9"
});
Think about how many combinations of overloads (or keeping track of nulls) you'd have to have to handle properties you may or may not want to supply to the object with the first method. This is a muchmore extensible and flexible approach.
考虑一下null您必须处理多少种重载组合(或跟踪s)来处理您可能想或不想用第一种方法提供给对象的属性。这是一个很大更具扩展性和灵活的方法。
2) Just allow it with a blank constructor, this would be much cleaner for the instantiation.
2)只允许它使用一个空白的构造函数,这对于实例化会更清晰。
3) Length/readability, especially with more than a few objects. Look at JSON, it's pretty clean/readable, again at least to me, if you like that style, creating arrays of your objects looks verysimilar in method #2.
3) 长度/可读性,尤其是多于几个对象。看看 JSON,它非常干净/可读,至少对我来说,如果你喜欢这种风格,在方法 #2 中创建对象数组看起来非常相似。
回答by Pointy
Well, the second way looks nice and is useful in the case of a "class" that has lots of setup options. However, be aware that you're actually constructing another object in the process.
嗯,第二种方法看起来不错,并且在具有很多设置选项的“类”的情况下很有用。但是,请注意,您实际上是在此过程中构造另一个对象。
I would advise you to read some code from one or another Javascript framework and find a style that appeals to you.
我建议你从一个或另一个 Javascript 框架中阅读一些代码,并找到一种吸引你的风格。

