在JavaScript中创建新对象

前端之家收集整理的这篇文章主要介绍了在JavaScript中创建新对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 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"
});

我喜欢第二种方式出现 – 代码是自我记录.但我的问题是:

>哪种方式“更好”?
>我可以使用第二种方式吗?
实例化对象的变量
已使用.定义的类型
“经典”的定义方式
具有该隐式的对象类型
构造函数
>如果我想创建一个数组
这些物品,还有其他的
考虑?

提前致谢.

解决方法

这真的很不错.这条路:
var anotherVariable = new someObjectType({
    property1:    "Some value for this named property",property2:    "This is the value for property 2"
});

…如果有超过2/3的参数通常会更好,因为它有助于提高可读性并且更容易避免可选参数问题(fn(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?

阵列有多大?究竟是什么阵列?性能可能值得考虑……

原文链接:https://www.f2er.com/js/159091.html

猜你在找的JavaScript相关文章