我正在通过执行以下操作来创建 javascript 对象:
function field(name,label){
this.name = name
this.label= label;
}
var a = new field("market","Mkt").
然后我将 a 分配给另一个对象。
object.newField = a;
第二种方式是直接创建一个新属性
object.2ndNewField = {
name: "market2",
label:"Mkt2"
}
我尝试读取其他函数中的对象。它们的行为不同,但是,当我将对象字符串化时,它看起来没问题。我创建的两个属性有什么区别?
顺便问一下,下面的对象有什么不同吗?
object.2ndNewField = {
"name": "market2",
"label":"Mkt2
}
最佳答案
区别在于,第一种情况下,创建的对象继承自field.prototype,然后是Object.prototype(即其内部的[[Prototype]]是field.原型(prototype),其内部 [[Prototype]] 是 Object.prototype),在第二种情况下,它仅继承自 Object.prototype。
另一种看待它的方式是:
object.newField instanceof field; // true
object.newField instanceof Object; // true
object.newField2 instanceof field; // false
object.newField2 instanceof Object; // true
或者继承链是:
object.newField -> field.prototype -> Object.prototype -> null
object.newField2 -> Object.prototype -> null
其中 '->' 表示“继承自”。
关于javascript - javascript创建对象的两种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6658631/