2016-01-25 100 views
0

我想從子模塊傳遞參數給父模塊構造函數,但由於某些原因參數未傳遞給父項。參數不會從子項傳遞給父項

這是孩子模塊:

var Child = (function() 
{ 
    /** 
    * @constructor 
    */ 
    var Child = function(offer) 
    { 
     _Parent.call(this, offer); 
    }; 

    /** 
    * Prototype. 
    */ 
    Child.prototype = Object.create(_Parent.prototype); 
    Child.prototype.construct = Child; 

    return Child; 
}()); 

而下面是父:

var _Parent = (function() 
{ 
    /** 
    * Contains the offer data. 
    * 
    * @type {{}} 
    */ 
    var offerData = {}; 

    /** 
    * @construct 
    */ 
    var _Parent = function(offer) 
    { 
     offerData = offer; 
    }; 

    /** 
    * Get the offer price. 
    * 
    * @param offering Index of the offering of which the price should be returned. 
    */ 
    var getPrice = function(offering) 
    { 
     if(typeof offering == 'undefined') 
     { 
      offering = 0; 
     } 

     return offerData[offering]['Prices']['PriceRow']['TotalPriceInclVAT']; 
    }; 

    /** 
    * Prototype. 
    */ 
    _Parent.prototype = { 
     construct : _Parent, 
     getPrice : getPrice 
    }; 

    return _Parent; 
}()); 

我試圖在getPrice()功能上的孩子是這樣的:

var child = new Child(offers); 
child.getPrice(); 

但我總是收到Uncaught TypeError: Cannot read property 'undefined' of undefined裏面的getPri每當我嘗試返回數據時,都會使用函數

+0

你確定'offer'不是'undefined'嗎? – Joseph

+0

我認爲你得到的錯誤是'Uncaught TypeError:無法讀取未定義的屬性'原型'。這是我複製代碼時得到的結果。 –

+0

@JosephtheDreamer剛剛重新檢查,我可以確認設置了「offers」。 – siannone

回答

1

您確定offers不是undefined

另一個問題是offerData不是一個實例屬性,而是一個定義了Parent構造函數的閉包內的變量。創建新實例時,它將在閉包中覆蓋offerData,消除之前實例定義的任何內容。

這是一樣的這樣做:

var foo = {}; 
 

 
function Parent(bar){ 
 
    foo = bar; 
 
} 
 

 
Parent.prototype.getFoo = function(){ 
 
    return foo; 
 
} 
 

 
function Child(bar){ 
 
    Parent.call(this, bar); 
 
} 
 

 
Child.prototype = Object.create(Parent.prototype); 
 

 
var hello = new Parent('Hello'); 
 
console.log(hello.getFoo()); // Hello 
 

 
var world = new Child('World'); 
 
console.log(world.getFoo()); // World 
 
console.log(hello.getFoo()); // World... wut???

這可以通過將offerData作爲一個實例屬性,因此它重視每個實例予以糾正。如果你想保持隱私的概念,你總是可以訴諸僞私人(按照慣例,前綴_)。

var _Parent = function(offer){ 
    this._offerData = offer; 
}; 
+0

你是對的,這個問題正是你描述的第二個問題(在關閉中聲明'offerData')。我理解它:如果'_Parent'是在一個對象內部聲明的,而不是一個閉包,它會起作用的,對吧? – siannone

0

這是因爲您只在定義Child後才定義_Parent。 您需要首先定義_Parent,然後Child因爲孩子使用父在該行

Child.prototype = Object.create(_Parent.prototype) 

我測試了它,和它的工作。

+0

'_Parent'在實際代碼中出現在'Child'之前。 – siannone

+0

你得到了什麼確切的錯誤信息?你能看到哪行代碼給出錯誤嗎? –

相關問題