[英]Accessing one javascript class inside another
我有两个javascript“类”。 其中一个应该是一种通用的,它将实例化另一个子类。
不知怎的,抛出一个undefined is not a function
错误:
this.progress = new Uploader.Progress({
matcher: options.matcher,
});
我使用下划线作为通过Rails资产管道require语句包含的依赖项。 这是完整的代码:
//= require underscore
if (typeof Uploader === "undefined") {
var Uploader = {};
}
(function() {
var Progress = Uploader.Progress = function(options) {
options || (options = {});
if(options.matcher) this.$matcher = $(options.matcher);
this.initialize.apply(this, arguments);
};
_.extend(Progress.prototype, {}, {
initialize: function() {
this.listen();
},
listen: function() {
this.$matcher.on("fileuploadprogress", function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find(".upload-progress").css({ "width": progress + "%" });
});
return this;
},
});
})();
(function() {
var Uploader = Project.Uploader = function(options) {
options || (options = {});
if(options.url) this.url = options.url;
if(options.matcher) this.$matcher = $(options.matcher);
this.progress = new Uploader.Progress({
matcher: options.matcher,
});
this.initialize.apply(this, arguments);
};
_.extend(Uploader.prototype, {}, {
initialize: function() {
this.listen();
},
listen: function() {
var _this = this;
this.$matcher.fileupload({
url: this.url,
type: "POST",
dataType: "json",
add: function(e, data) {
data.context = _this.$matcher.closest("form");
data.submit()
.success(function(result, textStatus, jqXHR) {
console.log("submitted");
});
},
});
return this;
},
});
})();
var uploader = new Project.Uploader({
matcher: "#video_file",
url: "/users/1/videos",
});
你在模块范围上创建一个上传者对象
if (typeof Uploader === "undefined") {
var Uploader = {};
}
但后来你创造了另一个本地的
var Uploader = Project.Uploader = function(options) ...
在本地对象中绑定任何内容* this在全局对象中不可见。 这是一种非常奇怪的风格。
当你说
this.progress = new Uploader.Progress({
matcher: options.matcher,
});
它匹配函数范围中Uploader defined in the
的Uploader defined in the
var Uploader = Project.Uploader = function(options) {
并且这个没有属性Progress
所以Uploader.Progress
是undefined
。 因此,错误。
要解决这个问题,请改变
var Uploader = Project.Uploader = function(options) {
至
var SomeOtherVariable = Project.Uploader = function(options) {
所以现在当你调用new Uploader.Progress({
它将开始在函数范围之外寻找Uploader
,因为它在函数范围内找不到它。将调用全局范围内Uploader.Progress
的正确函数集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.