我是 JavaScript 的初学者,正在尝试重构 API,但遇到了一个奇怪的问题。
我使用node
解释器来测试一些我想在我的重新设计中加入的代码,但是我遇到了一些意想不到的行为。
考虑在节点解释器中输入以下内容:
[In0] b
我期待一个 ReferenceError,如下所示。
[Out0]
ReferenceError: b is not defined
at repl:1:1
at REPLServer.defaultEval (repl.js:132:27)
at bound (domain.js:254:14)
at REPLServer.runBound [as eval] (domain.js:267:12)
at REPLServer.<anonymous> (repl.js:279:12)
at REPLServer.emit (events.js:107:17)
at REPLServer.Interface._onLine (readline.js:214:10)
at REPLServer.Interface._line (readline.js:553:8)
at REPLServer.Interface._ttyWrite (readline.js:830:14)
at ReadStream.onkeypress (readline.js:109:10)
下一个
[In1] 'b'
[Out1] 'b' // this is OK because it's a string
现在考虑一个 JSON 样式的对象:
[In2] var x = { 'b' : 'c' };
[Out2] { b : 'c' }
奇怪的是,引号被丢弃在 的键上x
。我愿意忽略这一点,尽管它令人困惑。
最后,
[In3] var y = { b : 'c' };
[Out3] { b : 'c' }
没有引号,解释器不会抱怨并产生与引号相同的结果。
我还注意到这种模式key
总是作为字符串返回:
for(var key in obj) {
key;
}
注意到这种行为,我尝试Bar
在我的 class中编写一个方法,Foo
定义如下:
function Foo(a) {
this.a = a;
this.Bar = function(attr, val) {
// attr doesn't need to be a string to be a key in object x
var x = { attr : val };
for(var key in x) {
//key DOES need to be a string to be used like this
this[key] = val;
}
}
}
本质上Bar
只是将键值对添加attr:val
到类型的对象中Foo
。
我尝试使用以下代码测试此代码:
[In4] var foo = new Foo('c');
[Out4] { a : 'c', Bar : [Function] } // this is OK. I expect this.
[In5] foo.Bar(hello, "World");
[Out5]
ReferenceError: hello is not defined
at repl:1:9
at REPLServer.defaultEval (repl.js:132:27)
at bound (domain.js:254:14)
at REPLServer.runBound [as eval] (domain.js:267:12)
at REPLServer.<anonymous> (repl.js:279:12)
at REPLServer.emit (events.js:107:17)
at REPLServer.Interface._onLine (readline.js:214:10)
at REPLServer.Interface._line (readline.js:553:8)
at REPLServer.Interface._ttyWrite (readline.js:830:14)
at ReadStream.onkeypress (readline.js:109:10)
谁能向菜鸟解释这种行为?当可以手动完成时,无法在方法中使用裸词作为键是非常令人沮丧的。