繁体   English   中英

在 javascript 中创建 object 的两种方法

[英]two ways of creating object in javascript

我正在通过执行以下操作创建 javascript object:

function field(name,label){
        this.name = name
        this.label= label;
}

var a = new field("market","Mkt").

然后我将一个分配给另一个 object。

object.newField = a;

第二种方法是直接创建一个新属性

object.2ndNewField = {
    name: "market2",
    label:"Mkt2"
}

我尝试在其他函数中读取对象。 它们的行为不同,但是,当我对 object 进行字符串化时,它看起来还可以。 我创建的两个属性有什么区别?

顺便说一句,下面的 object 有什么区别吗?

 object.2ndNewField = {
        "name": "market2",
        "label":"Mkt2
    }

The difference is that in the first case, the created object inherits from field.prototype then Object.prototype (ie its internal [[Prototype]] is field.prototype, whose internal [[Prototype]] is Object.prototype ), where as在第二种情况下,它仅继承自Object.prototype

另一种看待它的方式是:

object.newField instanceof field; // true
object.newField instanceof Object; // true

object.newField2 instanceof field; // false
object.newField2 instanceof Object; // true

或 inheritance 链是:

object.newField  -> field.prototype -> Object.prototype -> null

object.newField2 -> Object.prototype -> null

其中 '->' 表示“继承自”。

对于第一个选项...远离使用“新”。 如果“new”被错误地使用,或者在应该使用时被省略,你可能会严重影响你的全局命名空间。 另外,您必须小心在代码中的某些地方使用“this”,因为它可能会绑定到您认为不是的东西,甚至是您的全局数据。

在您提供的第二个选项中,您可以安全地将其用于仅用作数据/方法集合的对象(即不是“类类”行为)。 如果您想要一些可以使用私有和公共变量/方法创建多个实例并且可以从中继承的东西,那么您应该使用返回 object 的 function。

我在这里写了一篇关于如何安全地创建基础对象和使用 inheritance 的相当大的文章和示例。 如果你点击链接,你会明白为什么我没有在这篇文章中重新输入;)。

希望这可以帮助...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM