将Javascript命名空间闭包和原型一起使用会失败

Using Javascript namespace closures and prototype together fails?

本文关键字:失败 一起 原型 Javascript 命名空间 闭包      更新时间:2023-09-26

我在项目中使用名称空间,遵循以下模式:

// 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