开发者

Difference between var someObj = {}; and var someObj = new RealObj

So this is more of a question due to "not knowing the right word, thus I can't google it up" (I think).

What I have been wondering with javascript. One can create two "types" of Objects.

One would be: (or through using prototypes)

function Foo(){
    this.bar = function(){};
}

var foo = new Foo();

The other one bein开发者_如何学Pythong:

var foo = {
    bar : function(){}
};

The only few differences that I can come up with would be the fact that the former uses prototypes and can "extend" from other objects and also allows multiple instances where the latter can only have one instance and can't be extended (in the same way) (correct me if I am wrong)

However, in this case the variable named var foo has the exact same properties in both cases.

So for a concrete question: what is the name of the type of object being created (how can I search for more information on google for it) in the latter version and what differences are there between the two ways of creating an object?


The differences you are describing are correct.

The latter is called object literal notation and is more concise if you just want to create one object. But they are not two different types of objects. The object literal notation is more like a shortcut (but preferred) for creating objects.

You might want to read MDC - Working with objects.

The literal notation is actually the same as doing:

var foo = new Object();
foo.bar = function() {};

but as already said, it is more concise and easier to read.

Update:

Maybe one further difference worth mentioning: Calling new Foo() does not necessarily mean you will get a "Foo object" back. A constructor function can return any object. E.g. this is valid:

function Foo() {
    return new Bar();
}

var foo = new Foo(); // foo contains a "Bar object"

This can become useful for inheritance or if you want to e.g. cache instances and return the same instance for the same parameters passed to the function.


When you define an object using:

var foo = {};

It is literal. That object is an instant instance of the object. When you define an object like:

function Foo(){
    this.bar = function(){};
}

There is no instance created until you do new Foo().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜