将Javascript命名空间闭包和原型一起使用会失败
Using Javascript namespace closures and prototype together fails?
我在项目中使用名称空间,遵循以下模式:
// simply a namespace attic object
// parent to my worker objects
;(function( RoaringSky, undefined )
{
var opt = {
backend : ""
},
name = ""
;
RoaringSky.init = function( options ) {
jQuery.extend(opt,options);
console.log( 'RoaringSky.init complete');
};
// accessor
RoaringSky.opt = opt;
})(window.RoaringSky = window.RoaringSky || {});
这个名称空间的一个子对象是这样的:
RoaringSky.Day = (function() {
// constructor
var Day = function(){
var id = "none";
var name = "none";
var date = "none";
var periods = new Array();
this.periods = function() {
return periods;
};
};
// invoking day.time() fails - is not a function message
Day.prototype.time = function() {
return this.doSomthingWithDate(date);
};
return Day;
})(window.RoaringSky.Day = window.RoaringSky.Day || {});
我认为,就目前情况而言,这种模式运行良好。(欢迎批评)但这似乎阻碍了原型属性的使用。
也许我的理解是不完整的(我相信是的),但AFAIK,一旦我创建了一个对象-就像我上面的Day课程一样——我应该能够以的方式编写函数
Day.prototype.time = function() {
return this.doSomthingWithDate(date);
};
并且该类的所有实例都将继承该函数,因为它是构造函数的类对象Day()的属性;
然而,当我尝试这个:
var day = new Day();
day = new Date();
console.log( 'day.time: '+ day.time() );
我收到了"day.time()不是函数"的错误消息。
我做错了什么?这开始让我发疯了。
- Erik
耦合问题:
RoaringSky.Day = (function() {
// constructor
var Day = function(){
var id = "none";
var name = "none";
var date = "none";
var periods = new Array();
this.periods = function() {
return periods;
};
};
// invoking day.time() fails - is not a function message
Day.prototype.time = function() {
// can't use "date" here since it is not in scope
return this.doSomthingWithDate(date);
};
return Day;
})(window.RoaringSky.Day = window.RoaringSky.Day || {});
然后:
var day = new Day(); // Day is not a member of window, so this will only work when used in the `RoaringSky.Day` declaration.
day = new Date(); // you then override the day variable for some reason
console.log( 'day.time: '+ day.time() ); // time is not a function member of Date
相关文章:
- 转义符不能与innerHTML一起使用
- 当json解析空响应时,Whatwg-Fetch失败,我该如何防止它
- 高亮显示与数组字符串一起使用时文本插件中断
- JsFiddle在分叉后描述失败
- setTimeout可以与闭包内的函数一起使用吗
- 将依赖外部库的UMD模块与browserfy捆绑在一起
- Highcharts colorsByPoint与系列中的线性渐变一起使用时不起作用
- 如何将js库与typescript一起使用
- 将webpack和babel与父项目目录中的文件一起使用
- 将 Drag&Drop 与 jsTree 和 DataTables 一起使用
- Javascript-如何让脚本与Ajax请求的数据一起运行
- 将两个ext.TabPanels滚动到一起
- 将jQuery UI Timepicker Addon与React一起使用
- 为什么不'当单元测试出现解析错误时,我的因果报应测试会失败
- 当一些承诺失败时,如何继续使用$q.all()
- 失败:等待Protractor与页面同步时出错:“”;在窗口上找不到角度”;
- 把承诺和失败连在一起
- 将Javascript命名空间闭包和原型一起使用会失败
- Javascript乘法函数在一起时失败
- Ajax.请求在IE8/9中不能与CORS一起工作,静默失败