425

我最近偶然发现了Object.create()JavaScript 中的方法,并试图推断它与使用 创建对象的新实例有何不同new SomeFunction(),以及何时需要使用其中的一个。

考虑以下示例:

var test = {
  val: 1,
  func: function() {
    return this.val;
  }
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
  this.val = 1;
  this.func = function() {
    return this.val;
  };
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1 
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2

请注意,在两种情况下都观察到相同的行为。在我看来,这两种情况之间的主要区别是:

  • 中使用的对象Object.create()实际上形成了新对象的原型,而在new Function()声明的属性/函数中并不形成原型。
  • 您不能Object.create()像使用函数式语法那样使用语法创建闭包。考虑到 JavaScript 的词法(vs 块)类型范围,这是合乎逻辑的。

上述说法是否正确?我错过了什么吗?您什么时候会使用其中一种?

编辑:链接到上述代码示例的 jsfiddle 版本:http: //jsfiddle.net/rZfYL/

4

11 回答 11

485

很简单的说,new X就是Object.create(X.prototype)带有额外的运行constructor功能。(并为应该是表达式而不是 . 的结果的实际对象提供constructor机会。)returnthis

而已。:)

其余的答案只是令人困惑,因为显然没有其他人阅读new的定义。;)

于 2013-07-30T16:12:52.897 回答
255

Object.create 中使用的对象实际上形成了新对象的原型,而在 new Function() 中,声明的属性/函数不形成原型。

是的,Object.create构建一个直接从作为其第一个参数传递的对象继承的对象。

使用构造函数,新创建的对象继承自构造函数的原型,例如:

var o = new SomeConstructor();

在上面的例子中,o直接继承自SomeConstructor.prototype.

这里有一个区别,Object.create你可以创建一个不从任何东西继承的对象,Object.create(null);另一方面,如果你设置SomeConstructor.prototype = null;新创建的对象将继承自Object.prototype.

您不能像使用函数式语法那样使用 Object.create 语法创建闭包。考虑到 JavaScript 的词法(vs 块)类型范围,这是合乎逻辑的。

好吧,您可以创建闭包,例如使用属性描述符参数:

var o = Object.create({inherited: 1}, {
  foo: {
    get: (function () { // a closure
      var closured = 'foo';
      return function () {
        return closured+'bar';
      };
    })()
  }
});

o.foo; // "foobar"

请注意,我说的是 ECMAScript 第 5 版Object.create方法,而不是 Crockford 的 shim。

该方法开始在最新的浏览器上本地实现,请检查此兼容性表

于 2010-11-12T16:22:29.893 回答
218

以下是两个调用在内部发生的步骤:(
提示:唯一的区别在于第 3 步)


new Test()

  1. 创建new Object()对象
  2. 设置obj.__proto__Test.prototype
  3. return Test.call(obj) || obj; // normally obj is returned but constructors in JS can return a value

Object.create( Test.prototype )

  1. 创建new Object()对象
  2. 设置obj.__proto__Test.prototype
  3. return obj;

所以基本上Object.create不执行构造函数。

于 2013-01-29T23:23:33.457 回答
63

让我试着解释一下(更多关于博客):

  1. 当您编写Carconstructorvar Car = function(){}时,内部情况是这样的: 创建 javascript 对象时的原型链图 我们有一个不可访问的{prototype}隐藏链接,以及一个可访问且实际为 的链接。Function.prototype 和 Car.prototype 都隐藏了指向.Function.prototypeprototypeCar.prototypeconstructorCarObject.prototype
  2. 当我们想通过使用new操作符和create方法创建两个等价对象时,我们必须这样做:Honda = new Car();Maruti = Object.create(Car.prototype). 不同对象创建方法的原型链图 怎么了?

    Honda = new Car();— 当您创建这样的对象时,隐藏{prototype}属性将指向Car.prototype。所以在这里,{prototype}本田对象的 永远是Car.prototype——我们没有任何选择来改变{prototype}对象的属性。如果我想改变我们新创建的对象的原型怎么办?
    Maruti = Object.create(Car.prototype)— 当您创建这样的对象时,您有一个额外的选项来选择对象的{prototype}属性。如果你想要 Car.prototype 作为{prototype}然后将它作为参数传递给函数。如果您不想要任何{prototype}对象,那么您可以null像这样传递:Maruti = Object.create(null).

结论 — 通过使用该方法Object.create,您可以自由选择对象{prototype}属性。在new Car();中,你没有那种自由。

OO JavaScript 中的首选方式:

假设我们有两个对象ab

var a = new Object();
var b = new Object();

现在,假设a有一些方法b也想访问。为此,我们需要对象继承(只有当我们想要访问这些方法时才a应该是原型)。b如果我们检查原型,a然后b我们会发现它们共享原型Object.prototype

Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).

问题 -我们希望 objecta作为 的原型b,但这里我们b使用原型创建了 object Object.prototype解决方案——ECMAScript 5 引入Object.create(),轻松实现这种继承。如果我们这样创建对象b

var b = Object.create(a);

然后,

a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)

因此,如果您正在编写面向对象的脚本,那么Object.create()对于继承非常有用。

于 2014-09-03T03:45:22.913 回答
48

这个:

var foo = new Foo();

var foo = Object.create(Foo.prototype);

非常相似。一个重要的区别是new Foo实际运行构造函数代码,而Object.create不会执行代码,例如

function Foo() {
    alert("This constructor does not run with Object.create");
}

请注意,如果您使用Object.create()then 的两参数版本,您可以做更强大的事情。

于 2014-04-21T19:27:59.893 回答
23

区别在于所谓的“伪经典与原型继承”。建议在您的代码中仅使用一种类型,而不是混合使用这两种类型。

在伪经典继承(使用“new”运算符)中,假设您首先定义一个伪类,然后从该类创建对象。例如,定义一个伪类“Person”,然后从“Person”创建“Alice”和“Bob”。

在原型继承中(使用 Object.create),您直接创建一个特定的人“Alice”,然后使用“Alice”作为原型创建另一个人“Bob”。这里没有“类”;都是对象。

在内部,JavaScript 使用“原型继承”;“伪经典”方式只是一些糖。

有关这两种方式的比较,请参阅此链接

于 2013-06-22T00:28:32.360 回答
21
function Test(){
    this.prop1 = 'prop1';
    this.prop2 = 'prop2';
    this.func1 = function(){
        return this.prop1 + this.prop2;
    }
};

Test.prototype.protoProp1 = 'protoProp1';
Test.prototype.protoProp2 = 'protoProp2';
var newKeywordTest = new Test();
var objectCreateTest = Object.create(Test.prototype);

/* Object.create   */
console.log(objectCreateTest.prop1); // undefined
console.log(objectCreateTest.protoProp1); // protoProp1 
console.log(objectCreateTest.__proto__.protoProp1); // protoProp1

/* new    */
console.log(newKeywordTest.prop1); // prop1
console.log(newKeywordTest.__proto__.protoProp1); // protoProp1

概括:

1) 使用new关键字有两点需要注意;

a) 函数用作构造函数

b)function.prototype对象被传递给__proto__属性...或者__proto__不支持的地方,它是新对象寻找属性的第二个地方

2)与Object.create(obj.prototype)您一起构造一个对象(obj.prototype)并将其传递给预期的对象..不同之处在于现在新对象__proto__也指向 obj.prototype (请为此参考 xj9)

于 2013-12-21T00:18:11.673 回答
21

对象创建变体。


变体 1:' new Object() ' -> 不带参数的对象构造函数。

var p1 = new Object(); // 'new Object()' create and return empty object -> {}

var p2 = new Object(); // 'new Object()' create and return empty object -> {}

console.log(p1); // empty object -> {}

console.log(p2); // empty object -> {}

// p1 and p2 are pointers to different objects
console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

// empty object which is in fact Object.prototype
console.log(p1.__proto__); // {}

// empty object to which p1.__proto__ points
console.log(Object.prototype); // {}

console.log(p1.__proto__ === Object.prototype); // true

// null, which is in fact Object.prototype.__proto__
console.log(p1.__proto__.__proto__); // null

console.log(Object.prototype.__proto__); // null

在此处输入图像描述


变体 2:' new Object(person) ' -> 带参数的对象构造函数。

const person = {
    name: 'no name',
    lastName: 'no lastName',
    age: -1
}

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p1 = new Object(person);

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p2 = new Object(person);

// person, p1 and p2 are pointers to the same object
console.log(p1 === p2); // true
console.log(p1 === person); // true
console.log(p2 === person); // true

p1.name = 'John'; // change 'name' by 'p1'
p2.lastName = 'Doe'; // change 'lastName' by 'p2'
person.age = 25; // change 'age' by 'person'

// when print 'p1', 'p2' and 'person', it's the same result,
// because the object they points is the same
console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }

在此处输入图像描述


变体 3.1:' Object.create(person) '。将 Object.create 与简单对象“人”一起使用。'Object.create(person)' 将创建(并返回)新的空对象并将属性 '__proto__' 添加到同一个新的空对象。此属性“__proto__”将指向对象“人”。

const person = {
        name: 'no name',
        lastName: 'no lastName',
        age: -1,
        getInfo: function getName() {
           return `${this.name} ${this.lastName}, ${this.age}!`;
    }
}

var p1 = Object.create(person);

var p2 = Object.create(person);

// 'p1.__proto__' and 'p2.__proto__' points to
// the same object -> 'person'
// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(p1.__proto__);
console.log(p2.__proto__);
console.log(p1.__proto__ === p2.__proto__); // true

console.log(person.__proto__); // {}(which is the Object.prototype)

// 'person', 'p1' and 'p2' are different
console.log(p1 === person); // false
console.log(p1 === p2); // false
console.log(p2 === person); // false

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

console.log(p1); // empty object - {}

console.log(p2); // empty object - {}

// add properties to object 'p1'
// (properties with the same names like in object 'person')
p1.name = 'John';
p1.lastName = 'Doe';
p1.age = 25;

// add properties to object 'p2'
// (properties with the same names like in object 'person')
p2.name = 'Tom';
p2.lastName = 'Harrison';
p2.age = 38;

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

// { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// use by '__proto__'(link from 'p1' to 'person'),
// person's function 'getInfo'
console.log(p1.getInfo()); // John Doe, 25!

// use by '__proto__'(link from 'p2' to 'person'),
// person's function 'getInfo'
console.log(p2.getInfo()); // Tom Harrison, 38!

在此处输入图像描述


变体 3.2:' Object.create(Object.prototype) '。使用带有内置对象的 Object.create -> 'Object.prototype'。'Object.create(Object.prototype)' 将创建(并返回)新的空对象并将属性 '__proto__' 添加到同一个新的空对象。此属性“__proto__”将指向对象“Object.prototype”。

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
var p1 = Object.create(Object.prototype);

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
var p2 = Object.create(Object.prototype);

console.log(p1); // {}

console.log(p2); // {}

console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

console.log(p2.prototype); // undefined

console.log(p1.__proto__ === Object.prototype); // true

console.log(p2.__proto__ === Object.prototype); // true

在此处输入图像描述


变体 4:'新的 SomeFunction() '

// 'this' in constructor-function 'Person'
// represents a new instace,
// that will be created by 'new Person(...)'
// and returned implicitly
function Person(name, lastName, age) {

    this.name = name;
    this.lastName = lastName;
    this.age = age;

    //-----------------------------------------------------------------
    // !--- only for demonstration ---
    // if add function 'getInfo' into
    // constructor-function 'Person',
    // then all instances will have a copy of the function 'getInfo'!
    //
    // this.getInfo: function getInfo() {
    //  return this.name + " " + this.lastName + ", " + this.age + "!";
    // }
    //-----------------------------------------------------------------
}

// 'Person.prototype' is an empty object
// (before add function 'getInfo')
console.log(Person.prototype); // Person {}

// With 'getInfo' added to 'Person.prototype',
// instances by their properties '__proto__',
// will have access to the function 'getInfo'.
// With this approach, instances not need
// a copy of the function 'getInfo' for every instance.
Person.prototype.getInfo = function getInfo() {
    return this.name + " " + this.lastName + ", " + this.age + "!";
}

// after function 'getInfo' is added to 'Person.prototype'
console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

// create instance 'p1'
var p1 = new Person('John', 'Doe', 25);

// create instance 'p2'
var p2 = new Person('Tom', 'Harrison', 38);

// Person { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// Person { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// 'p1.__proto__' points to 'Person.prototype'
console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

// 'p2.__proto__' points to 'Person.prototype'
console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

console.log(p1.__proto__ === p2.__proto__); // true

// 'p1' and 'p2' points to different objects(instaces of 'Person')
console.log(p1 === p2); // false

// 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p1'-instance's data
console.log(p1.getInfo()); // John Doe, 25!

// 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p2'-instance's data
console.log(p2.getInfo()); // Tom Harrison, 38!

在此处输入图像描述

于 2018-03-22T17:29:25.390 回答
12

在内部Object.create这样做:

Object.create = function (o) {
    function F() {}
    F.prototype = o;
    return new F();
};

语法只是消除了 JavaScript 使用经典继承的错觉。

于 2010-11-12T16:19:13.173 回答
12

根据这个答案这个视频 new关键字做接下来的事情:

  1. 创建新对象。

  2. 将新对象链接到构造函数 ( prototype)。

  3. 使this变量指向新对象。

  4. 使用新对象执行构造函数并隐式执行return this

  5. 将构造函数名称分配给新对象的属性constructor

Object.create只执行1st2nd步骤!!!

于 2017-07-27T19:55:01.580 回答
0

Object.create(Constructor.prototype)是的一部分new Constructor

这是new Constructor实现

// 1. define constructor function

      function myConstructor(name, age) {
        this.name = name;
        this.age = age;
      }
      myConstructor.prototype.greet = function(){
        console.log(this.name, this.age)
      };

// 2. new operator implementation

      let newOperatorWithConstructor = function(name, age) {
        const newInstance = new Object(); // empty object
        Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

// 3. produce new instance

      const instance = new myConstructor("jun", 28);
      const instance2 = newOperatorWithConstructor("jun", 28);
      console.log(instance);
      console.log(instance2);
      

new Constructor实现包含Object.create方法

      newOperatorWithConstructor = function(name, age) {
        const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining

        const bindedConstructor = myConstructor.bind(newInstance); // this binding
        bindedConstructor(name, age); // execute binded constructor function

        return newInstance; // return instance
      };

      console.log(newOperatorWithConstructor("jun", 28));
于 2020-09-27T18:26:14.900 回答