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
到哪里去了?这是模块化我的代码的最好方法吗?这样我就可以把它分解成不同的文件。
谢谢。
相当宽泛的问题这里有一些要点
-
尝试像这样声明远程
function Remote() {...}
这将在窗口中设置远程功能(最顶层的"This"),因此您将拥有window. Remote .
在构造函数中初始化变量。
使用new创建对象的实例,然后操作该实例。
你需要在远程实例中调用,否则"this"将默认为window对象,你可以使用call、apply或bind来解决这个问题。
查看此链接以获得更深入的解释http://phrogz.net/JS/classes/OOPinJS2.html
2检查自执行函数的模块化。例如,你可以这样写
(function myPrivateFunction() {
...
})()
这隔离了私有函数的作用域,避免污染全局命名空间。我强烈推荐大家看看John Resig的书《Javascript忍者的秘密》
相关文章:
- 关于引入外部javascript文件的问题&css通过https
- Javascript,文件输入和FormData问题
- Node.js服务器问题-已添加“/"在浏览器中查找文件时
- Express Routes-多个文件的问题
- 使用ajax在html中加载html文件时出现的问题
- 尝试从csv文件中检索单个值时出现问题
- 在javascript中检查文件扩展名的问题
- 加载本地json文件问题
- 外部JavaScript文件问题
- Java 程序文本文件问题
- Django + skelJS / 静态文件问题 / 对 CSS 中图像的引用
- 获取 JSON 文件问题
- Wordpress-自定义页面包括第二个导致函数文件问题的自定义页面
- 外部js文件问题
- 加载javascript文件问题
- JS prototype.namespace单独的文件问题
- 将bootstrap主题安装到Rails 4应用程序中- javascript文件问题
- AngularJS图表文件问题
- 流星客户端外部Javascript文件问题
- Javascript类方法加载json文件问题