gpt4 book ai didi

javascript - 访问一个 javascript 类中的另一个类

转载 作者:行者123 更新时间:2023-12-02 17:25:40 24 4
gpt4 key购买 nike

我有两个 javascript“类”。其中一个应该是一种通用类,它将实例化另一个子类。

不知怎的,这会抛出一个未定义不是函数错误:

    this.progress = new Uploader.Progress({
matcher: options.matcher,
});

我使用下划线作为通过 Rails Assets 管道 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",
});

最佳答案

当你说

this.progress = new Uploader.Progress({
matcher: options.matcher,
});

它与函数作用域中定义的 uploader 匹配,即

var Uploader = Project.Uploader = function(options) {

并且这个没有属性 Progress,因此 Uploader.Progress未定义。因此,出现错误。

要解决这个问题,请更改

var Uploader = Project.Uploader = function(options) {

var SomeOtherVariable = Project.Uploader = function(options) {

现在,当您调用 new Uploader.Progress({) 时,它将开始在函数作用域之外查找 Uploader,因为它不会在函数作用域内找到它。将调用全局范围内为 Uploader.Progress 设置的正确函数。

关于javascript - 访问一个 javascript 类中的另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23518868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com