且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

'this'关键字可以在RequireJS模块中使用吗?

更新时间:2023-11-10 11:59:46

不,因为Require.js不对此。您应该将模块重写为实例对象:

No, because Require.js doesn't do any magic binding for this. You should rewrite your module to be an instance object:

define(['config', 'jquery'], function(config, $) {
    function obj() {
        this.initNav();
        this.initTwitter();
        this.initFullSiteLink();
    }
    obj.prototype = {
        doesObjPropertyExist: function (/*...*/) { /*...*/ },
        shortenURL: function (/*...*/) { /*...*/ },
        initTwitter: function (/*...*/) { /*...*/ },
        initFullSiteLink: function (/*...*/) { /*...*/ },
        initNav: function (/*...*/) { /*...*/ },
        omniture: function (/*...*/) { /*...*/ }
    };
    return obj;
});

require(['that_main_module'], function (obj) {
    var newObj = new obj();
});