The expression new C(arg1, arg2)
:
Assuming C is a JavaScript function (otherwise you get an error):
- Creates a new empty object (no properties)
- 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.
- Calls the function
C
with 'this
' set to the new object, and with the supplied arguments.
- 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]);