2016-01-25 68 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

你得到了什么确切的错误信息?你能看到哪行代码给出错误吗? –

相关问题