我正在尝试将子模块中的参数传递给父模块构造函数,但由于某些原因,该参数未传递给父模块。
这是子模块:
writer
以下是父母:
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()
但是每当我尝试返回数据时,我都会在 getPrice 函数中收到var child = new Child(offers);
child.getPrice();
。
答案 0 :(得分: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;
};
答案 1 :(得分:0)
这是因为您在定义_Parent
后才定义Child
。
您需要首先定义_Parent
,然后定义Child
,因为Child使用行中的父级
Child.prototype = Object.create(_Parent.prototype)
我测试了它,它起作用了。