如何将原型 属性 添加到现有对象

How to add prototype property to existing object

数组中的对象很少,我想从工厂添加一些道具到类型为 - 日期的对象。

我不需要从此对象中删除旧值。我尝试这样做:

  angular.forEach($scope.things, function(item) {
    if(item.type === 'date') {
      item = DateFactory.prototype.createFactory();
    }
  })

但是它不起作用,我哪里错了? Plunker example

对于原型链接,请使用以下语法:-

item = Object.create(Date);

更改 forEach 中的 item 不会改变项目。您需要使用 obj[key] 代替:

angular.forEach($scope.things, function(item, key, obj) {
    if(item.type === 'date') {
      obj[key] = DateFactory.prototype.createFactory();
    }
  })

已更新plunker

此外,您应该 return 来自工厂的日期对象的实例:

return new date();

..然后调用方法:

obj[key] = DateFactory.createFactory()