javascript中创建对象的两种方法
我通过执行以下操作来创建 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
}
I'm creating javascript object by doing something like:
function field(name,label){
this.name = name
this.label= label;
}
var a = new field("market","Mkt").
Then I assign a to another object.
object.newField = a;
The second way of doing it is to create a new property directly
object.2ndNewField = {
name: "market2",
label:"Mkt2"
}
I try to read the objects in other functions. They behave differently, however, when i stringify the object, it looks ok. What's the difference between the two properties i created?
btw is there any difference of the following object?
object.2ndNewField = {
"name": "market2",
"label":"Mkt2
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不同的是,第一种情况,创建的对象继承自field.prototype,然后继承Object.prototype(即它的内部[[Prototype]]是field.prototype,其内部[[Prototype]]是Object.prototype),与第二种情况一样,它仅继承自Object.prototype。
另一种看待它的方式是:
或者继承链是:
其中“->”意思是“继承自”。
The difference is that in the first case, the created object inherits from field.prototype then Object.prototype (i.e. its internal [[Prototype]] is field.prototype, whose internal [[Prototype]] is Object.prototype), where as in the second case it inherits only from Object.prototype.
Another way to look at it is:
or the inheritance chains are:
where '->' means "inherits from".
对于第一个选项...远离使用“new”。如果“new”使用错误,或者在应该使用时省略,则可能会对全局命名空间产生严重影响。另外,在代码中的某些地方使用“this”时必须小心,因为它可能绑定到您认为不存在的东西,甚至绑定到全局数据。
在您提供的第二个选项中,您可以安全地将其用于仅用作数据/方法集合的对象(即不是“类类”行为)。如果您想要可以使用私有和公共变量/方法创建多个实例并且可以继承的东西,那么您应该使用返回对象的函数。
我写了一篇相当大的文章和示例这里< /a> 如何安全地创建基础对象并使用继承。如果您点击该链接,您就会明白为什么我没有在这篇文章中重新输入所有内容;)。
希望这有帮助...
For the First option...Stay away from using "new". You can badly effect your global namespace if "new" is used wrong, or omitted when it should be used. Plus you have to be careful with the use of "this" in some places within your code, as it could be bound to something that you don't think it is, or even to your global data.
In your 2nd option you gave, you can safely use it for objects that are only used as a collection of data/methods (i.e. not "class-like" behavior) . If you want something that you can create multiple instances of with private and public variables/methods and can be inherited from, then you should use a function that returns an object.
I did a pretty big write up and example here of how to safely create base objects and use inheritance. If you follow the link, you will see why I didn't retype it all on this post ;).
Hope this helps...