簡體   English   中英

在角度工廠內設置* .prototype方法不起作用

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

我正在創建一個封裝和可注入類型的角度工廠,可以像這樣對它們進行更新:

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

function() {

    function PaymentStream(){

        this._endingBalance = null;
    }

    PaymentStream.prototype.serialize = function() {

        // method body here
    };

    return PaymentStream;

   }]);
})();

當我通過new PaymentStream()創建PaymentStream時,似乎只調用了構造函數。 如果我不使用prototype而只是在構造函數中定義方法,則它可以工作,但是我將在每個實例中重新定義函數。

知道為什么不設置這些原型嗎?

編輯

這是在外部使用的方式。

    function addStreamFunctions(stream) {

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

因此,根據您的編輯,工廠確實可以正常工作。 是你用它的方式,你的問題angular.merge d為new編輯對象與另一個對象,所以它的類型不是PaymentStream了,得到的對象變成了“通用” object

如果流是普通對象,您可以做的是在PaymentStream的構造函數中傳遞stream變量,然后在構造函數中手動進行合並。 就像是

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;
    });

}

然后像

function addStreamFunctions(stream) {

    var stream = new PaymentStream(stream);

}

此代碼未經測試,請告訴我它是否有效:)

由於您正在使用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