Object.create(原型)和Object(原型)之间的区别

时间:2015-04-24 11:49:09

标签: javascript oop object prototypal-inheritance

快速但难以谷歌的问题:

var child = Object.create(parent.prototype);

var child = Object(parent.prototype); 

它们相同吗?

编辑:

我的问题是由两个用于实现寄生组合继承模式的inheritPrototype函数的例子引起的。

function inheritPrototype(childObject, parentObject) {
    var copyOfParent = Object.create(parentObject.prototype);
    copyOfParent.constructor = childObject;
    childObject.prototype = copyOfParent;
}

a bug/limitation in Android-Gradle

function inheritPrototype(subType, superType){
    var prototype = object(superType.prototype); 
    prototype.constructor = subType; 
    subType.prototype = prototype;
}

http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/

3 个答案:

答案 0 :(得分:3)

不,他们不相同见下文:

  1. Object.create(prototype)将创建一个新的原型从<{1}}继承作为参数传递

  2. prototypeObject(obj)将创建new Object(obj)的新实例,同时调用构造函数。

  3. 现在,由于原型也是javascript对象,因此差异可能很小。但是obj可以处理可能需要参数的构造函数,而Object.create则不会

    this SO related answer中的更多信息(例如差异继承,自定义属性等)

    <强>参考

    1. Object.create on MDN
    2. new Object on MDN
    3. OP编辑后

      更新

      在我的OOP javascript框架Classy.js中,对于较旧的浏览器,new Object()附近存在此填充,这可能会让您了解差异之间的进一步问题:

      Object.create

      此polyfill可以处理 Create = Obj.create || function( proto, properties ) { var Type = function () {}, TypeObject; Type[PROTO] = proto; TypeObject = new Type( ); TypeObject[__PROTO__] = proto; if ( 'object' === typeOf(properties) ) defineProperties(TypeObject, properties); return TypeObject; } 之类的任意构造函数(带参数),并确保正确分配Object.create。使用__proto__的模式是尝试(弱地)引用Object(prototype)

答案 1 :(得分:3)

不,他们不一样:

  

对象(X)新对象(X) Object.create(X.prototype)

相同

Object(X)将创建对象并运行Constructor(即新创建的对象继承自构造函数的原型)。 Object.create(X.prototype)正在创建另外运行Constructor的对象。

  

对象(X)新对象(X)不是 Object.create()

Object.create()正在创建对象而不运行Constructor(即它将创建一个不从任何东西继承的对象)

答案 2 :(得分:1)

New Object将子项设置为父项:

var parent = {name : 'proto'};
var child = new Object(parent);
console.log(child === parent);//=true
//if I set child.name it will change parent.name

Object create返回一个对象实例,它使用第一个参数作为proto(原型链中使用的第一个原型)。

child = Object.create(parent);
console.log(child === parent);//=false
//I can set child.name because it will be shadowed
//  and will not change parent.name
console.log(child.hasOwnProperty('name'));//=false

有关原型的更多信息,请访问:https://stackoverflow.com/a/16063711/1641941