SoFunction
Updated on 2025-03-03

Introduction to creating objects in JavaScript

For object creation, in addition to using literals and new operators, in the ECMAScript 5 standard, it can also be done using (). The () function accepts 2 objects as parameters: the first object is required to represent the prototype of the created object; the second object is optional to define the various properties of the created object (such as writable, enumerable).

Copy the codeThe code is as follows:

var o = ({x:1, y:7});
(o);//Object {x=1, y=7}
(o.__proto__);//Object {x=1, y=7}

Calling null as the first parameter will generate an object without a prototype, which will not have any basic Object properties (for example, using the + operator for this object will throw an exception because there is no toString() method):

Copy the codeThe code is as follows:

var o2 = (null);
("It is " + o2);//Type Error, can't convert o2 to primitive type

For browsers that only support the ECMAScript 3 standard, you can use Douglas Crockford to perform () operation:

Copy the codeThe code is as follows:

if (typeof !== 'function') {
    = function (o) {
        function F() {}
        = o;
        return new F();
    };
}
newObject = (oldObject);