繁体   English   中英

JS prototype.namespace用于单独的文件问题

[英]JS prototype.namespace for separate file issue

我刚刚开始尝试使原型范例成为一个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走了吗? 问题2-这是模块化代码的最佳方法,因此我可以将其分解为不同的文件。

谢谢。

相当广泛的问题,所以这里有一些要点

  1. 尝试像这样声明远程

    函数Remote(){...}

这将在窗口(顶级“ this”)中设置“远程”功能,因此您将拥有window.remote。

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

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

您需要从远程实例中调用,否则“ this”将默认为窗口对象。您可以使用调用,应用或绑定来解决此问题。

请查看此链接,以获取更深入的说明http://phrogz.net/JS/classes/OOPinJS2.html

2检查自执行功能的模块化。 例如,您可以做类似的事情

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

这样可以将您的私有功能范围隔离开,并且避免污染全局名称空间。 我强烈建议您查看约翰·雷西格(John Resig)的书“ JavaScript忍者的秘密”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM