简体   繁体   中英

How to add prototype property to existing object

I have few objects in array and I want to add some props from factory to object with type - date.

I don't need to remove old values from this object. I try to do it in this way:

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

but it doesn't work, where I'm wrong? Plunker example

Changing the item within the forEach does not mutate the item. You need to use obj[key] instead:

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

Updated plunker

Also, you should return the instance of your date object from the factory:

return new date();

..and then just call the method:

obj[key] = DateFactory.createFactory()

要链接原型,请使用以下语法:

item = Object.create(Date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM