私は適切に機能するために多くの部分で構成されるライブラリを開発しようとしています。プロトタイプ関数(IIFE)からインスタンスのパブリックプロパティへのアクセス
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)
は私が基本脳クラスからコンストラクタで定義されたプロパティを使用することを防止する、常にundefined
であるということです。
似たようなことをする他の質問を読んだことがありますが、私のようなIIFEを使用しているものはありません。
EDIT:すべてのみんなありがとう、私は両方のあなたの答えの組み合わせを使用しました、ここでは最終結果です:あなたのコンテキストがBrainStudy
ない
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;
}());
「BrainStudy」をどのように作成しますか? '新しいBrainStudy()'を使用していますか? 'new'演算子を使用してこのオブジェクトを作成しないという問題があると思われます。 – VadimB
私はそれを使用しています.Blinモジュールの' study() 'メソッドを見てください。 – GiamPy
はい、あなたの 'of'メソッドはどうやって呼びますか? 'this'は' window'ではなくクラスインスタンスへのポインタでなければなりません。 'of'メソッドを呼び出すところであなたのコードを共有してください – VadimB