Home >Web Front-end >JS Tutorial >Introduction to using Object.create() to create objects in JavaScript_javascript skills

Introduction to using Object.create() to create objects in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:23:071467browse

For object creation, in addition to using literals and the new operator, in the ECMAScript 5 standard, you can also use Object.create(). The Object.create() function accepts 2 objects as parameters: the first object is required and represents the prototype of the created object; the second object is optional and is used to define various properties of the created object (for example, writable , enumerable).

Copy code 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}

Calling Object.create() with null as the first argument will generate an object without a prototype, which will not have any basic Object properties (for example, since there is no toString() method, using operations on this object symbol will throw an exception):

Copy code 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 Douglas Crockford’s method to perform the Object.create() operation:

Copy code 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);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn