Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the new operator work in JavaScript?

Probably the least understood part of JavaScript, standing beside the prototype chain.

So the question is: how does...

new dataObj(args);  

...actually create an object, and define its prototype chain/constructors/etc?

Best is to show an alternative, to fully understand this keyword.

like image 796
PicoCreator Avatar asked Jul 19 '11 16:07

PicoCreator


People also ask

How do you use the new operator?

Use of the new operator signifies a request for the memory allocation on the heap. If the sufficient memory is available, it initializes the memory and returns its address to the pointer variable. The new operator should only be used if the data object should remain in memory until delete is called.

What is new operator with example?

The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

What is the use of new keyword?

The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to constructs and returns an object of the constructor function.

What is the use of new operator in Java?

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.


2 Answers

The new operator uses the internal [[Construct]] method, and it basically does the following:

  • Initializes a new native object
  • Sets the internal [[Prototype]] of this object, pointing to the Function prototype property.
    • If the function's prototype property is not an object (a primitive values, such as a Number, String, Boolean, Undefined or Null), Object.prototype is used instead.
  • After creating the object, it calls the function, providing the object as its this value.
  • If the return value of the called function, is a primitive, the object created internally is returned.
  • Otherwise, if an object is returned, the object created internally is lost.

An equivalent implementation of what the new operator does, can be expressed like this (assuming that the ECMAScript 5 Object.create method is available):

function NEW(f) {   var obj, ret, proto;    // Check if `f.prototype` is an object, not a primitive   proto = Object(f.prototype) === f.prototype ? f.prototype : Object.prototype;    // Create an object that inherits from `proto`   obj = Object.create(proto);    // Apply the function setting `obj` as the `this` value   ret = f.apply(obj, Array.prototype.slice.call(arguments, 1));    if (Object(ret) === ret) { // the result is an object?     return ret;   }   return obj; }  // Example usage: function Foo (arg) {   this.prop = arg; } Foo.prototype.inherited = 'baz';  var obj = NEW(Foo, 'bar'); obj.prop;          // 'bar' obj.inherited;     // 'baz' obj instanceof Foo // true 
like image 166
Christian C. Salvadó Avatar answered Sep 19 '22 18:09

Christian C. Salvadó


The expression new C(arg1, arg2):

Assuming C is a JavaScript function (otherwise you get an error):

  1. Creates a new empty object (no properties)
  2. Sets the prototype of the new object to the value of the "prototype" property of C.
    • Note: The default value of prototype for a function is an object (automatically created when the function is declared) with its prototype set to Object.prototype and a constructor property pointing back to the function C.
    • Note: The terminology can be confusing. The property named "prototype" is not the same as the prototype of the object. Only functions have the property named "prototype", but all objects have a prototype.
  3. Calls the function C with 'this' set to the new object, and with the supplied arguments.
  4. If calling the function C returns an object, this object is the result of the expression. Otherwise the newly created object is the result of the expression.

An alternative to new in ECMAScript 5 would be to use the builtin Object.createObject method.

new C(arg1, arg2) would be equivalent to:

var obj = Object.createObject(C.prototype); C.apply(obj, [arg1, arg2]); 

Standard JavaScript does not allow you to explicitly set the prototype of an object, so Object.createObject cannot be implemented in the language itself. Some implementations does allow it through the non-standard property __proto__. In that case, new C can be simulated like this:

var obj = {}; obj.__proto__ = C.prototype; C.apply(obj, [arg1, arg2]); 
like image 31
JacquesB Avatar answered Sep 19 '22 18:09

JacquesB