当存在赋值语句时,在javascript文件中提供名称空间
我有一段javascript代码,我想为其添加一个名称空间。在该代码中,有一个赋值操作发生在函数之外。有人能告诉我如何把它放在命名空间中吗?代码如下所示当存在赋值语句时,在javascript文件中提供名称空间,javascript,jquery,html,Javascript,Jquery,Html,我有一段javascript代码,我想为其添加一个名称空间。在该代码中,有一个赋值操作发生在函数之外。有人能告诉我如何把它放在命名空间中吗?代码如下所示 var mynameSpace={ canvasPanel:{}, stage:{}, someShape:{}, drawLineGraph:function(dataList,color,baseY) { //Create a shape this.dataList=dataList; this.index=0; this.current
var mynameSpace={
canvasPanel:{},
stage:{},
someShape:{},
drawLineGraph:function(dataList,color,baseY)
{
//Create a shape
this.dataList=dataList;
this.index=0;
this.currentDay=1;
},
myNameSpace.drawLineGraph.prototype = new createjs.Shape(); //Getting the problem here
myNameSpace.drawLineGraph.prototype.constructor = drawLineGraph; //Getting the problem here**
,
drawLegend:function(){
}
};
只需将
drawLineGraph
替换为this即可。drawLineGraph
您可以将函数和后续赋值包装到另一个函数中,然后立即调用它,如下所示:
drawLineGraph: (function() {
var f = function(dataList, color, baseY {
// Create a shape
... function code ...
};
f.prototype = new createjs.Shape();
... more assignments ...
return f; // this will be assigned to drawLineGraph
})(),
看起来您正在对象文字定义内执行原型赋值。因此,当您试图修改mynameSpace的原型时,它的drawLineGraph属性不存在。将drawLineGraph原型特性指定移到对象文字下方
var mynameSpace={
canvasPanel:{},
stage:{},
someShape:{},
drawLineGraph:function(dataList,color,baseY)
{
//Create a shape
this.dataList=dataList;
this.index=0;
this.currentDay=1;
},
drawLegend:function(){
}
};
myNameSpace.drawLineGraph.prototype = new createjs.Shape(); //No longer a problem
myNameSpace.drawLineGraph.prototype.constructor = drawLineGraph; //No longer a problem
谢谢你的回答。