This article mainly introduces how to use Object in JavaScript. create () describes how to create an object. This article first explains the syntax and then describes how to create an instance. If you want to create an object, refer to create an object. In addition to using the literal and new operators, in the ECMAScript 5 standard, you can also use Object. create. 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 ).
The 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 ):
The 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:
The 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 );