我想创建一个可在脚本中随处访问的全局函数,用于处理 Graph
对象 - 构造它、更新它等。
我做了一个函数:
function GraphFactory(){
this.initNames = function(nodes) {
nodeNames = nodes;
}
this.getNodeNames = function() {
return nodeNames;
}
this.addNameToNodeNames = function(name) {
nodeNames.push(name);
return true;
}
}
然后当我尝试使用
填充它时 GraphFactory.initNames(['hello','boo'])
它说GraphFactory.initNames
不是一个函数...
我如何使用它来用节点名称填充该图形对象,然后使用 GraphFactory.getNodeNames()
获取它们的列表?
谢谢!
最佳答案
在名为 nodeNames
的类上设置一个属性,然后实例化该对象。
function GraphFactory(){
this.nodeNames= [];
this.initNames = function(nodes) {
this.nodeNames = nodes;
}
this.getNodeNames = function() {
return this.nodeNames;
}
this.addNameToNodeNames = function(name) {
this.nodeNames.push(name);
return true;
}
}
let graphFactory = new GraphFactory();
graphFactory.initNames(['hello','boo'])
console.log(graphFactory.getNodeNames());
关于javascript - 如何在 Javascript 中创建全局变量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55597091/