JS prototype.namespace单独的文件问题

JS prototype.namespace for separate file issue

本文关键字:文件 问题 单独 prototype namespace JS      更新时间:2023-09-26

我刚刚开始尝试让我的头周围的原型范式,使一个jquery插件。

我的代码是这样工作的:

(function(window, $){
    var Remote = function(elem, options) {
        this.elem = elem;
        this.$elem = $(elem);
        this.options = options;
        this.p = [];
    };
    Remote.prototype = {
        defaults: {
            message: 'Hello world!'
        },
        init: function() {
            this.config = $.extend({}, this.defaults, this.options, this.metadata);
            ...
        },
        findPath: function() {
            var t = this.p.length;
            ...
        }
    };
    Remote.prototype.constructor = Remote;
    Remote.defaults = Remote.prototype.defaults;
    $.fn.remote = function(options) {
        return this.each(function() {
            new Remote(this, options).init();
        });
    };
})(window, jQuery);

所以现在我试着让它更模块化,有能力分成多个文件(请纠正我,如果我去任何这个错误):

var Remote = function(elem, options) {
    this.elem = elem;
    this.$elem = $(elem);
    this.options = options;
    this.p = [];
};
Remote.prototype = {
    defaults: {
        message: 'Hello world!'
    },
    init: function() {
        this.config = $.extend({}, this.defaults, this.options, this.metadata);
        ...
    }
};
// I'd like to put this object into path.js
Remote.prototype.path = {
    find: function() {
        var t = this.p.length;
        // this.p is undefined
        ...
    }
};
Remote.prototype.constructor = Remote;
Remote.defaults = Remote.prototype.defaults;
(function(window, $){
    $.fn.remote = function(options) {
        return this.each(function() {
            new Remote(this, options).init();
        });
    };
})(window, jQuery);

通过在Remote.prototype中设置命名空间,我似乎失去了this的作用域。

Q1 - this到哪里去了?这是模块化我的代码的最好方法吗?这样我就可以把它分解成不同的文件。

谢谢。

相当宽泛的问题这里有一些要点

  1. 尝试像这样声明远程

    function Remote() {...}

这将在窗口中设置远程功能(最顶层的"This"),因此您将拥有window. Remote .

在构造函数中初始化变量。

使用new创建对象的实例,然后操作该实例。

你需要在远程实例中调用,否则"this"将默认为window对象,你可以使用call、apply或bind来解决这个问题。

查看此链接以获得更深入的解释http://phrogz.net/JS/classes/OOPinJS2.html

2检查自执行函数的模块化。例如,你可以这样写

(function myPrivateFunction() {
...
})()

这隔离了私有函数的作用域,避免污染全局命名空间。我强烈推荐大家看看John Resig的书《Javascript忍者的秘密》