我在一个文件中有这个解析器类:
module.exports = function Parser() {
this.myVar = "";
var parse = function (inputString) {
this.myVar = "somethingAfterParse";
}
return {
initWithString: function(inputString) {
parse(inputString)
},
name: this.myVar
};
};
然后,在“主”文件 js 中,我以这种方式使用解析器:
var Parser = require("./Parser.js");
var parserInstance = new Parser();
parserInstance.initWithString("somestring");
console.log("Parser var:", parserInstance.myVar);
没有错误,但日志打印出一个空名称.. 为什么?
最佳答案
这是我会做的:
function Parser() {
this.myVar = "";
}
Parser.prototype.initWithString = function (inputString) {
this.myVar = "somethingAfterParse";
};
module.exports = Parser;
你的方法,注释
module.exports = function Parser() {
// public property "myVar" of any new Parser object
this.myVar = "";
// anonymous function assigned to private variable "parse"
var parse = function (inputString) {
// "this" will likely be the global object here, dangling error
this.myVar = "somethingAfterParse";
}
// return API object - unnecessary and makes debugging harder (*)
return {
// anonymous function that calls private "parse" function
initWithString: function(inputString) {
// calling parse without defining "this", definitely an error (**)
parse(inputString)
},
// the above is equivalent to and therefore better written as
// initWithString: parse,
// copy of (!) public property myVar, definitely an error (***)
name: this.myVar
};
};
当您省略冗余位(并利用原型(prototype)链)时,您最终会得到我上面建议的结果。
* 我知道这是定义对象公共(public)接口(interface)的流行方法。我个人不是很喜欢。从 JS 构造函数返回一个对象有效地破坏了 new
的用途。运算符(operator):
- 您使对象的用户无法访问分配给
this
的所有内容在构造函数内部之前,就像你的this.myVar
. 您得到一袋没有类型信息的属性。从技术上讲这是可行的,但在调试过程中并不好。比较:
function A() { this.a = "A"; return { a: "a" }; } function B() { this.b = "B"; } new A(); // Object {a: "a"} new B(); // B {b: "B"}
** this
函数内部将引用调用该函数的任何对象(上下文)。
通常点符号会为您做到这一点:object.method()
套this
至 object
里面method
.
但是您不调用 parse()
作用于任何对象。任何在没有上下文的情况下调用的函数都在全局对象的上下文中运行(在浏览器中是 Window
)。
您可能需要使用 var self = this;
来指定上下文早些时候和parse.apply(self, arguments)
在initWithString
里面 body 。
最后,整个“让我们将对象作为 API 返回”的方法让事情变得比他们需要的更困难。
*** 在 JavaScript 中,基本类型总是按值分配。就像数字或 bool 值一样,您不能引用字符串。将它们分配给其他变量会复制它们。
关于javascript - 带有变量的 Nodejs 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794372/