在JavaScript中创建新对象

时间:2010-04-16 13:40:07

标签: javascript javascript-objects

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

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

  1. 哪种方式“更好”?

  2. 我可以使用第二种方式吗? 实例化对象的变量 已使用。定义的类型 “经典”的定义方式 具有该隐式的对象类型 构造

  3. 如果我想创建一个数组 这些物品,还有其他的 考虑?

  4. 提前致谢。

4 个答案:

答案 0 :(得分:7)

这真的很难品尝。这样:

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'))。

另一个考虑因素是表现。以传统方式传递参数会更快,但这种速度增益仅在性能敏感的情况下变得非常重要。

  

我是否可以使用第二种方式来实例化一个对象类型的变量,该变量是使用“经典”方式定义的,使用该隐式构造函数定义对象类型?

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

var _constructor = SomeConstructorFunction;

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

我不建议仅仅为了风格而混淆第三方API。

  

如果我想创建这些对象的数组,还有其他注意事项吗?

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

答案 1 :(得分:3)

创建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;
};

Javascript: The Good Parts第52页,我强烈推荐它: - )

答案 2 :(得分:2)

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"

});  

考虑一下你需要处理的属性的多少组合(或跟踪null),你可能想要或不想用第一种方法提供给对象的属性。这是一种很多更具可扩展性和灵活性的方法。

2)只允许使用空白构造函数,这对于实例化来说会更加清晰。

3)长度/可读性,特别是对于多个对象。看看JSON,它非常干净/可读,至少对我来说,如果你喜欢这种风格,创建对象的数组看起来非常类似于方法#2。

答案 3 :(得分:1)

嗯,第二种方式看起来不错,对于有很多设置选项的“类”很有用。但是,请注意,您实际上是在构建过程中构建另一个对象。

我建议你从一个或另一个Javascript框架中读取一些代码,找到一个吸引你的风格。