Differencebetween 'New Object()' and Object Literal Notation

What is the difference between `new Object()` and object literal notation?

They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.

These

person = new Object() /*You should put a semicolon here too.  
It's not required, but it is good practice.*/
-or-

person = {
property1 : "Hello"
};

technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.

The "something unusual" that someone could do would be to shadow or assign to the default Object global:

// Don't do this
Object = 23;

In that highly-unusual case, new Object will fail but {} will work.

In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).

difference between `new Object()` and object literal notation?

Objects can be defined by either of these two methods:

var abc = {};
var abc = new Object();

There is minimal difference between the two, however the first method is preferred by most.

If Scanner is of type Function then you instantiate it like so:

var scan = new Scanner();

The Scanner function might have been created like this:

function Scanner(total = 5){
this.scans = total;
}

You could use this function like this:

var scan = new Scanner();

console.log(scan); // Output: Object
console.log(scan.scans); // Output: 5

scan = new Scanner(100);

console.log(scan.scans); // Output: 100

scan.scans = 50;

console.log(scan.scans); // Output: 50

var scan2 = { scans: 5 };

console.log(scan2); // Output: Object
console.log(scan2.scans); // Output: 5

Javascript: What is the difference between object literal notation and the object constructor?

A constructor gives an object a sense of identity. It's essentially a blueprint for how to create it which can be re-used. It is very similar to and often confused with a class in classical OOP.

If you frequently have a bunch of "car" objects and there are methods or properties which often go with all cars, you can create a Car constructor to help encapsulate it.

function Car(numPassengers) {
this.numPassengers = numPassengers;
}

Car.prototype = {
accelerate: function () {
// blah
},
brake: function () {
// blah
}
};

var jetta = new Car(4);
var bmwZ4 = new Car(2);

An object literal is a way to pass a just-in-time object whose structure and creation does not need to be re-used. To compare to classical OOP, similar to a Map in Java (except that javascript object literals can still have methods). A common use case is a function which takes a bunch of possible parameters, but each one is optional.

function someActionThatTakesOptionalParams(options) {
if (options.doAlert) {
alert(options.doAlert);
}
if (options.someOtherProperty) {
// do some work
}
}

someActionThatTakesOptionalParams({
doAlert: 'this will show up in an alert box',
someOtherProperty: 5,
hello: 'world'
});

It's also a convenient way to just model data that gets passed to something else with no methods attached. For example, you have an API that takes JSON:

$.ajax({
url: 'someApiEndpoint',
method: 'get',
params: {
x: 5,
y: 10
}
});

Choosing between object creation via constructor and object-literal syntax

I mean the constructor-way must be in there for some reason ...

The Object constructor was originally the only way to create an object. The object initializer syntax ({}) was added in JavaScript 1.2, the updated JavaScript in Netscape Navigator 4.0 in 1997.

There are several reasons to prefer initializer syntax to the Object constructor:

  • It's shorter
  • It's more expressive, particularly when using property initializers
  • It can't be overridden/shadowed (whereas Object can be)1

In contrast, there is basically no reason to use Object to create objects except indirectly, when using a variable that might point to the Object function or might point to some other function, e.g.:

function constructAndInit(ctor, props) {
var obj = new ctor();
if (props) {
for (var key in props) {
obj[key] = props[key];
}
}
return obj;
}

// Maybe use use Object...
var foo = constructAndInit(Object);

// ...or maybe you use somnething else
var bar = constructAndInit(NiftyThingy);

We do, of course, routinely use the Object function without calling it to create objects:

  • Any time we want to get access to the root object prototype, Object.prototype
  • To use the functions that are properties of Object, like Object.create, Object.defineProperty, and such

1 "can't be overridden/shadowed (whereas Object can be)" Here's an example of shadowing Object:

function foo() {    var Object = {        foo: "bar"    };
// ...later... var o = new Object(); // fails}foo();

Adding function to prototype vs object literal (using this)

You are correct.

function A() {}
A.prototype.printNum = function() {};

function B() {
this.printNum = function() {};
}

var a1 = new A();
var a2 = new A();
console.log(a1.printNum == a2.printNum); // true

var b1 = new B();
var b2 = new B();
console.log(b1.printNum == b2.printNum); // false

In the first case, there is one instance of the function implementation printNum. In the second case, each instance of B has its own function printNum.

Having many functions uses more memory and the object creation is more expensive, but prototype lookups can become a performance problem as well (according to some people, I'd still prefer them).


There is another difference: Many libraries use object.hasOwnProperty() to determine whether a property "is part of" an object. object.hasOwnProperty() returns true if the property is defined on the object itself instead of being inherited.

var a = new A();
cosole.log(a.hasOwnProperty('printNum')); // false

var b = new B();
console.log(b.hasOwnProperty('printNum')); // true

For example, JSON.stringify uses this to check which properties should be included in its output. This does not really matter as we are talking about functions (which will be ignored by JSON.stringify), but let's use this example:

function C() {}
C.prototype.myvar = "Hello world!";

function D() { this.myvar = "Hello world!"; }

var c = new C();
var d = new D();
console.log(JSON.stringify(c)); // {}
console.log(JSON.stringify(d)); // {"myvar":"Hello world!"}

Before ES5, it was pretty difficult to make variables "final" (Java) / "readonly" (C#) in JavaScript. The second approach allows to do so:

function C(finalVariable) {
this.getMyVariable = function() { return finalVariable };
}

I do not say that this is good style or should be used in practice (it is not even safe as getMyVariable may be overwritten as well), it is just a fact: Using this function instantiation allows to access variables from the constructor without exposing them to other functions through object properties.

Is there any difference between these three ways of creating an array?

Using [] is more secure and reliable than using new Array(). The former is actually recommended. This is because the value of Array can be overridden. Also, [] is faster compared to new Array().

Take a look at these related questions:

  • What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
  • JSLint: “Use the array literal notation []” for var os_map = {}
  • What's wrong with var x = new Array();
  • Is JavaScript 's “new” Keyword Considered Harmful?

A related link:

  • JSLint wants you to avoid new.

To clarify what "overridden" means, you can do something like this:

function Array() {
alert("I am not really an array! BWAHAHAHAHAHA!");
}

Now when you do new Array(); you will get an alert, which is obviously not what you want.

In short, there really is no pressing need to to use new Array() and it doesn't buy you anything more compared to using the literal [].

Difference between {} and new Object()

There is no difference (technically). {} is just a shortcut for new Object().

However, if you assign an object literal, you may directly form a new object with multiple properties.

var myData = {
name: 'ATOzTOA',
size: 'atoztoa'
};

..which might feel more convenient. Also, it reduces the access on the object and is ultimately faster. But that is about microoptimizations. More important is that its a lot less to type.

What is the 'new' keyword in JavaScript?

It does 5 things:

  1. It creates a new object. The type of this object is simply object.
  2. It sets this new object's internal, inaccessible, [[prototype]] (i.e. __proto__) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
  3. It makes the this variable point to the newly created object.
  4. It executes the constructor function, using the newly created object whenever this is mentioned.
  5. It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead.

Note: constructor function refers to the function after the new keyword, as in

new ConstructorFunction(arg1, arg2)

Once this is done, if an undefined property of the new object is requested, the script will check the object's [[prototype]] object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript.

The most difficult part about this is point number 2. Every object (including functions) has this internal property called [[prototype]]. It can only be set at object creation time, either with new, with Object.create, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with Object.getPrototypeOf(someObject). There is no other way to set or read this value.

Functions, in addition to the hidden [[prototype]] property, also have a property called prototype, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.


Here is an example:

ObjMaker = function() {this.a = 'first';};
// ObjMaker is just a function, there's nothing special about it that makes
// it a constructor.

ObjMaker.prototype.b = 'second';
// like all functions, ObjMaker has an accessible prototype property that
// we can alter. I just added a property called 'b' to it. Like
// all objects, ObjMaker also has an inaccessible [[prototype]] property
// that we can't do anything with

obj1 = new ObjMaker();
// 3 things just happened.
// A new, empty object was created called obj1. At first obj1 was the same
// as {}. The [[prototype]] property of obj1 was then set to the current
// object value of the ObjMaker.prototype (if ObjMaker.prototype is later
// assigned a new object value, obj1's [[prototype]] will not change, but you
// can alter the properties of ObjMaker.prototype to add to both the
// prototype and [[prototype]]). The ObjMaker function was executed, with
// obj1 in place of this... so obj1.a was set to 'first'.

obj1.a;
// returns 'first'
obj1.b;
// obj1 doesn't have a property called 'b', so JavaScript checks
// its [[prototype]]. Its [[prototype]] is the same as ObjMaker.prototype
// ObjMaker.prototype has a property called 'b' with value 'second'
// returns 'second'

It's like class inheritance because now, any objects you make using new ObjMaker() will also appear to have inherited the 'b' property.

If you want something like a subclass, then you do this:

SubObjMaker = function () {};
SubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!
// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype
// is now set to the object value of ObjMaker.prototype.
// The modern way to do this is with Object.create(), which was added in ECMAScript 5:
// SubObjMaker.prototype = Object.create(ObjMaker.prototype);

SubObjMaker.prototype.c = 'third';
obj2 = new SubObjMaker();
// [[prototype]] property of obj2 is now set to SubObjMaker.prototype
// Remember that the [[prototype]] property of SubObjMaker.prototype
// is ObjMaker.prototype. So now obj2 has a prototype chain!
// obj2 ---> SubObjMaker.prototype ---> ObjMaker.prototype

obj2.c;
// returns 'third', from SubObjMaker.prototype

obj2.b;
// returns 'second', from ObjMaker.prototype

obj2.a;
// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype
// was created with the ObjMaker function, which assigned a for us

I read a ton of rubbish on this subject before finally finding this page, where this is explained very well with nice diagrams.

Difference between new Array(..) and [..] in JavaScript?

Yes, for that case they are the same.

There is a difference if you have only one item, and it's numeric. This will create an array with a single item:

var myNumbers = [42];

but this will create an array with the length 42:

var myNumbers = new Array(42);


Related Topics



Leave a reply



Submit