gpt4 book ai didi

javascript - 从原型(prototype)函数 (IIFE) 访问实例公共(public)属性

转载 作者:行者123 更新时间:2023-12-01 04:04:13 25 4
gpt4 key购买 nike

我正在尝试开发一个由更多部分组成的库,以便正常运行。

var Brain = (function () {
var publics = {
studies: {
"ManagedVehicles": "\\Brain\\Studies\\ManagedVehicles"
}
};

publics.study = function (study) {
if (! publics.studies.hasOwnProperty(study)) {
throw new BrainInvalidStudy(study + " study does not exist.");
}

return new BrainStudy(study);
}

return publics;
}());

function BrainInvalidStudy(message) {
this.message = message;
// Use V8's native method if available, otherwise fallback
if ("captureStackTrace" in Error)
Error.captureStackTrace(this, BrainInvalidStudy);
else
this.stack = (new Error()).stack;
}

var BrainStudy = (function () {

function BrainStudy (study) {
this.study = study;
}

BrainStudy.prototype = (function (userId) {
var publics = {};
var self = this;

console.log(this);

function query (data) {
return $.ajax('/api/brain/study', {
data: data
});
}

publics.of = function (userId) {
return new Promise(function (resolve, reject) {
console.log(this); // window
console.log(self); // window
console.log(self.study); // undefined

query({
what: self.study,
who: userId
}).done(function (response, textStatus, jqXHR) {
resolve(response);
}).fail(function (jqXHR, textStatus, errorThrown) {
reject();
})
});
}

return publics;
}());

return BrainStudy;
}());

BrainInvalidStudy.prototype = Object.create(Error.prototype);
BrainInvalidStudy.prototype.name = "BrainInvalidStudy";
BrainInvalidStudy.prototype.constructor = BrainInvalidStudy;

问题是 console.log(self.study) 始终是 未定义,这阻止我使用 Brain 基类的构造函数中定义的属性。

我读过其他做类似事情的问题,但没有一个像我一样使用 IIFE。

编辑:谢谢大家,我结合了你们的答案,这是最终结果:

var BrainStudy = (function () {

function BrainStudy (study) {
this.study = study;
}

(function (prototype) {
function query (data) {
return $.ajax('/api/brain/study', {
data: data
});
}

prototype.of = function (userId) {
var self = this;

return new Promise(function (resolve, reject) {
query({
what: self.study,
who: userId
}).done(function (response, textStatus, jqXHR) {
resolve(response);
}).fail(function (jqXHR, textStatus, errorThrown) {
reject();
})
});
}
}(BrainStudy.prototype));

return BrainStudy;
}());

最佳答案

您应该在 public.of 中创建 self 变量:

publics.of = function (userId) {
var self = this;
return new Promise(function (resolve, reject) {

query({
what: self.study,
who: userId
}).done(function (response, textStatus, jqXHR) {
resolve(response);
}).fail(function (jqXHR, textStatus, errorThrown) {
reject();
})
});
}

目前,self 等于 window,因为它是在匿名函数中初始化的,而不是在任何对象的上下文中初始化。

关于javascript - 从原型(prototype)函数 (IIFE) 访问实例公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41956277/

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