我正在嘗試從另一個文件導入一個函數。我嘗試這樣做:
主要.js:
const oauth2 = require('./utils/oauth2');
function startOAuth() {
var token = oauth2.OAuth2.getToken();
}
實用程序/oauth2.js:
module.exports = (function() {
window.OAuth2 = {
/**
* Initialize
*/
init: function() {
this._key = "token";
},
/**
* Get Token
*
* @return OAuth2 access token if it exists, null if not.
*/
getToken: function() {
try {
return window['localStorage'][this._key];
}
catch(error) {
return null;
}
}
};
OAuth2.init();
})();
我收到以下錯誤:
未捕獲的類型錯誤:無法讀取未定義的屬性(讀取“getToken”)
我做錯了什麼?為什麼 NodeJS 找不到getToken()
函數?非常感謝您的幫助!
PS:我知道在這裡說我是初學者是錯誤的,但我是初學者;)
您正在導出調用函數而沒有返回的結果。您分配給 的module.exports
是一個稱為立即調用函數表達式的模式。
如果您改為分配OAuth
給一個變量,init()
在聲明後立即調用,然後將其導出,則代碼應該可以工作。
const OAuth2 = {
/**
* Initialize
*/
init: function () {
this._key = "";
},
/**
* Get Token
*
* @return OAuth2 access token if it exists, null if not.
*/
getToken: function () {
try {
return window["localStorage"][this._key];
} catch (error) {
return null;
}
},
};
OAuth2.init();
module.exports = OAuth2;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句