For object creation, in addition to using literals and new operators, in the ECMAScript 5 standard, Object.create() can also be used. The Object.create() function accepts two 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).
The code copy 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}
Calling Object.create() as the first parameter will generate an object without a prototype, which will not have any basic Object properties (for example, since there is no toString() method, using the + operator for this object will throw an exception):
The code copy 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 Douglas Crockford's method to perform the Object.create() operation:
The code copy is as follows:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);