开发者

two ways of creating object in javascript

开发者 https://www.devze.com 2023-03-19 07:42 出处:网络
I\'m creating javascript object by doing something like: function field(name,label){ this.name = name this.label= label;

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
    开发者_运维百科}


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:

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

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

or the inheritance chains are:

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

object.newField2 -> Object.prototype -> null

where '->' means "inherits from".


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消