[英]Not able to access namespace variable in js file
a.js a.js
// @global-constants
var App = {
constant: function() {
constant.prototype.CONST1 = 'abc';
}
};
module.exports = App;
not able to access in say b.js
using App.constant.CONST1
, it says undefined why? 无法访问说
b.js
使用App.constant.CONST1
,它说不确定的,为什么?
there are two problems with you code: 您的代码有两个问题:
1.) App.constant
would return a class(technically a function), but what you want is it's object, can be created using a new
keyword, so it becomes, (new App.constant).CONST1
. 1.)
App.constant
将返回一个类(从技术上讲是一个函数),但是您想要的是它的对象,可以使用new
关键字创建它,因此它变成了(new App.constant).CONST1
。
2.) constant.prototype.CONST1
would not work, because constant
is not the name of your anonymous function, so I gave it a name foo
and it becomes foo.prototype.CONST1
. 2.)
constant.prototype.CONST1
不起作用,因为constant
不是您的匿名函数的名称,所以我给它命名为foo
,它变成foo.prototype.CONST1
。
the modified code: 修改后的代码:
var App = {
constant: function foo() {
foo.prototype.CONST1 = 'abc';
}
};
console.log((new App.constant).CONST1);
If you just want to create a set of "constants", all you need is an object: 如果只想创建一组“常量”,则只需要一个对象:
// @global-constants
var App = {
constant: {
CONST1: 'abc';
}
};
To learn more about how prototypes work (so that you know when to use them and when not), I recommend to read this article on MDN . 要了解有关原型工作方式的更多信息(以便您知道何时使用原型以及何时不使用原型),我建议阅读MDN上的这篇文章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.