Object.create()可以做任何工厂功能无法做到的事情吗?

时间:2018-04-27 19:43:53

标签: javascript object

Douglas Crockford编制了Object.create()规范。

但我已经读过他不再使用它了。

  

......他也停止使用Object.create(虽然它只是添加了   对他而言语。)

Douglas Crockford speaking about the new good parts of JavaScript in 2014

如果Crockford不再使用Object.create()需要吗?它提供的任何东西都无法通过工厂功能以某种方式复制吗?

2 个答案:

答案 0 :(得分:2)

object.create功能归结为:

Object.create = function(someObj){
    function noOP(){
    };
    noOP.prototype = someObj;
    return new noOP;
}

目的是创建一个可以在不修改上游原型的情况下添加内容的对象。它被设计为一种捷径。因此,没有任何Object.create可以做到工厂函数(或任何函数)无法做到的事情。做任何与你产生共鸣的事情。

答案 1 :(得分:1)

然后主要的事情Object.create做的是促进原型继承。像这样的模式:

function Animal(name) {
  this.name = name;
}

Animal.prototype = {
  sayName: function() {
    console.log(this.name);
  }
}

function Tiger(name) {
  Animal.call(this, name);
}

Tiger.prototype = Object.create(Animal.prototype, {
  scream: {
    value: function() {
      console.log('Roar!');
    }
  },
  constructor: {
    value: Tiger
  }
});

tiger = new Tiger('fido');

tiger.scream();
tiger.sayName();
console.log(Animal.prototype.isPrototypeOf(tiger.constructor.prototype));

复制起来并不那么简单。 Object.create有polyfill,所以你可以在没有它的情况下实现相同的功能,但最后,它的功能是非常具体的,并且在某些模式中可能很有用。

道格拉斯·克罗克福德之所以不使用它,是因为他不再使用原型继承(至少从那个视频开始)。所以你可以做这样的事情,而不是使用原型和Object.create

function Animal(name) {
  var self = {};
  self.name = name;
  self.sayName = function() {
    console.log(self.name);
  }
  return self;
}

function Tiger(name) {
  var self = Animal(name);
  self.scream = function() {
    console.log('Roar!');
  }
  return self
}

tiger = Tiger('fido');

tiger.scream();
tiger.sayName();
console.log(Animal.prototype.isPrototypeOf(tiger.constructor.prototype));

你会得到或多或少相同的结果,但它并不完全相同。在这种情况下,Tiger并没有真正继承Animal。这是另一种模式。您可以决定使用它,但这是一种不同的方法,而不是取代Object.create模式的方法。

随着ES6的使用越来越多,通常Object.create将被替换,但是按类而不是工厂功能。支持类时,您可以执行以下操作:

class Animal {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}

class Tiger extends Animal {
  constructor(name) {
    super(name);
  }

  scream() {
    console.log('Roar!');
  }
}

tiger = new Tiger('fido');

tiger.scream();
tiger.sayName();
console.log(Animal.prototype.isPrototypeOf(tiger.constructor.prototype));

这与第一种模式大致相同。所以是的,Object.create做了一些特定的事情,但它仍然以类的方式被替换。