[英]Not able to access namespace variable in js file
a.js
// @global-constants
var App = {
constant: function() {
constant.prototype.CONST1 = 'abc';
}
};
module.exports = App;
無法訪問說b.js
使用App.constant.CONST1
,它說不確定的,為什么?
您的代碼有兩個問題:
1.) App.constant
將返回一個類(從技術上講是一個函數),但是您想要的是它的對象,可以使用new
關鍵字創建它,因此它變成了(new App.constant).CONST1
。
2.) constant.prototype.CONST1
不起作用,因為constant
不是您的匿名函數的名稱,所以我給它命名為foo
,它變成foo.prototype.CONST1
。
修改后的代碼:
var App = {
constant: function foo() {
foo.prototype.CONST1 = 'abc';
}
};
console.log((new App.constant).CONST1);
小提琴演示 。
如果只想創建一組“常量”,則只需要一個對象:
// @global-constants
var App = {
constant: {
CONST1: 'abc';
}
};
要了解有關原型工作方式的更多信息(以便您知道何時使用原型以及何時不使用原型),我建議閱讀MDN上的這篇文章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.