残りのクラスの「名前空間」として使用する 1 つのルート オブジェクトを定義しました。このルート オブジェクト内には、TOOLS と PRESENTATION の 2 つのクラスがあります。PRESENTATION クラスでは、TOOLS からパブリック メソッドの 1 つを呼び出す必要があります。console.log
このコードの問題の実行のすべてのステップで遊んだ後にわかるように、にreturn xhr.responseText
何も返さないで、tools.getData(configPath)
最終的にundefined
in console.log(pres.config)
.
コード:
// Create Namespace
var AppSpace = AppSpace || {};
// Class and Constructor
AppSpace.Tools = function() {
//public methodts
this.test = function(arg) {
return arg
}
this.getData = function(path) {
var xhr = new XMLHttpRequest();
xhr.open('GET', path, false);
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (xhr.status !== 0 && xhr.status !== 200) {
if (xhr.status === 400) {
console.log("Could not locate " + path);
} else {
console.error("app.getData " + path + " HTTP error: " + xhr.status);
}
return;
}
return xhr.responseText;
};
xhr.send();
}
}
// Class and Constructor
AppSpace.Presentation = function(initName, initfPath){
//private properties
var configPath = initfPath || 'config.json';
var configData = null;
var name = initName || 'Unnamed Presentation';
//private methods
var getConfigContent = function() {
return tools.getData(configPath);
}
var getConfigData = function() {
return JSON.parse(getConfigContent);
}
//public methodts
//public properties
this.name = null;
this.config = null;
this.debug = null;
//logic
this.name = name;
this.config = getConfigContent();
}
//execution
var tools = new AppSpace.Tools();
var pres = new AppSpace.Presentation('Some Name');
pres.debug = tools.test('value passed')
console.log(pres.debug);
console.log(pres.config);
console.log(pres.name);
ブラウザ コンソールの出力は次のとおりです。
value passed js-oop.dev:99
**undefined js-oop.dev:100**
Some Name js-oop.dev:101
誰でもこれについて少しアドバイスできますか? ティア。