gpt4 book ai didi

javascript - 在 JavaScript 中创建新对象

转载 作者:数据小太阳 更新时间:2023-10-29 04:31:36 26 4
gpt4 key购买 nike

我是 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');

但我见过以这种方式创建对象的新实例的其他方法:

var anotherVariable = new someObjectType({
property1: "Some value for this named property",
property2: "This is the value for property 2"
});

我喜欢第二种方式出现的方式 - 代码是 self 记录的。但我的问题是:

  1. 哪种方式“更好”?

  2. 我可以用第二种方式吗实例化一个对象的变量已使用定义的类型定义的“经典”方式隐含的对象类型构造函数?

  3. 如果我想创建一个数组这些对象,还有其他的吗考虑因素?

提前致谢。

最佳答案

这真的很不合口味。这样:

var anotherVariable = new someObjectType({
property1: "Some value for this named property",
property2: "This is the value for property 2"
});

... 如果参数超过 2/3,通常会更好,因为它有助于提高可读性并更容易避免可选参数问题 (fn(null,null,null,123')).

另一个考虑因素是性能。以传统方式传递参数会更快,但这种速度提升只会在对性能非常敏感的情况下变得显着。

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?

不容易。如果您想通过使用散列而不是仅仅传递参数来实例化构造函数,并且您无法控制源,那么您可以“包装”它:

var _constructor = SomeConstructorFunction;

SomeConstructorFunction = function(hash) {
return new _constructor(hash.property1, hash.property2);
};

不过,我真的不建议为了风格而乱用第三方 API。

If I want to create an array of these objects, are there any other considerations?

数组有多大?数组到底是做什么用的?性能可能值得考虑...

关于javascript - 在 JavaScript 中创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2653299/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com