Home  >  Article  >  Web Front-end  >  JavaScript中使用Object.create()创建对象介绍_javascript技巧

JavaScript中使用Object.create()创建对象介绍_javascript技巧

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

对于对象的创建,除了使用字面量和new操作符,在ECMAScript 5标准中,还可以使用Object.create()来进行。Object.create()函数接受2个对象作为参数:第一个对象是必需的,表示所创建对象的prototype;第二个对象是可选的,用于定义所创建对象的各个属性(比如,writable、enumerable)。

复制代码 代码如下:

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}

将null作为第一个参数调用Object.create()将生成一个没有prototype的对象,该对象将不会具有任何基本的Object属性(比如,由于没有toString()方法,对这个对象使用+操作符会抛出异常):

复制代码 代码如下:

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

对于仅支持ECMAScript 3标准的浏览器,可以用Douglas Crockford的方法来进行Object.create()操作:

复制代码 代码如下:

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