繁体   English   中英

无法访问js文件中的名称空间变量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM