我在项目中使用命名空间,方法是:
// 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()不是函数'错误消息。
我做错了什么?这开始让我疯狂。
答案 0 :(得分:0)
夫妻问题:
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