Use Object. create () in JavaScript to create objects.
In addition to the literal and new operators, you can use Object. create () to create an Object in the ECMAScript 5 standard. Object. the create () function accepts two objects as parameters: the first object is required, indicating the prototype of the created object. The second object is optional, defines the attributes of the created object (such as writable and enumerable ).
Copy codeThe Code is as follows:
Var o = Object. create ({x: 1, y: 7 });
Console. log (o); // Object {x = 1, y = 7}
Console. log (o. _ proto _); // Object {x = 1, y = 7}
Use null as the first parameter to call the Object. create () will generate an Object without prototype, and the Object will not have any basic Object attributes (for example, because there is no toString () method, the + operator will throw an exception for this object ):
Copy codeThe Code is as follows:
Var o2 = Object. create (null );
Console. log ("It is" + o2); // Type Error, can't convert o2 to primitive type
For browsers that only support the ECMAScript 3 standard, you can use the Douglas Crockford method to perform the Object. create () operation:
Copy codeThe Code is as follows:
If (typeof Object. create! = 'Function '){
Object. create = function (o ){
Function F (){}
F. prototype = o;
Return new F ();
};
}
NewObject = Object. create (oldObject );