简体   繁体   English

在角度工厂内设置* .prototype方法不起作用

[英]Setting *.prototype methods inside angular factory not working

I'm creating an angular factory that encapsulates and injectable type that can be new-ed up as such: 我正在创建一个封装和可注入类型的角度工厂,可以像这样对它们进行更新:

(function() {
angular
  .module('app')
  .factory('PaymentStream', [

function() {

    function PaymentStream(){

        this._endingBalance = null;
    }

    PaymentStream.prototype.serialize = function() {

        // method body here
    };

    return PaymentStream;

   }]);
})();

When I create a PaymentStream via new PaymentStream() only the constructor seems to have been called. 当我通过new PaymentStream()创建PaymentStream时,似乎只调用了构造函数。 If I don't use prototype and just define the methods inside the constructor it works but then I'm redefining the functions with each instance. 如果我不使用prototype而只是在构造函数中定义方法,则它可以工作,但是我将在每个实例中重新定义函数。

Any idea why those prototypes are not being set? 知道为什么不设置这些原型吗?

Edit 编辑

Here is how it is being used in the outside. 这是在外部使用的方式。

    function addStreamFunctions(stream) {

        angular.merge(stream, new PaymentStream());
    }

So basing on your edit, The factory was indeed working correctly. 因此,根据您的编辑,工厂确实可以正常工作。 The problem is the way you used it, you angular.merge d the new ed object with another object, so its type is not a PaymentStream anymore, the resulting object became a 'generic' object 是你用它的方式,你的问题angular.merge d为new编辑对象与另一个对象,所以它的类型不是PaymentStream了,得到的对象变成了“通用” object

If the stream is a plain object, what you can do is pass the stream variable in the constructor of PaymentStream and do the merging manually inside your constructor function. 如果流是普通对象,您可以做的是在PaymentStream的构造函数中传递stream变量,然后在构造函数中手动进行合并。 Something like 就像是

function PaymentStream(stream){

    this._endingBalance = null;

    var keys = Object.keys(stream); //get all properties from the stream

    keys.forEach(function(key){
       this[key] = stream[key];   //put each one in the instance of your object;
    });

}

then use it like 然后像

function addStreamFunctions(stream) {

    var stream = new PaymentStream(stream);

}

this code is untested, please tell me if it worked or not :) 此代码未经测试,请告诉我它是否有效:)

Since you are working with factory you need to return an instance of the object, in this case a new instance of PaymentStream 由于您正在使用factory您需要返回该对象的实例,在这种情况下,将返回一个PaymentStream的新实例。

(function() {
  angular.module('my-app').factory('PaymentStream', [function() {
    function PaymentStream() {
      this._endingBalance = null;
    }

    PaymentStream.prototype.serialize = function() {
      // method body here
    };

    return new PaymentStream();
  }]);
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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