【发布时间】:2015-07-26 21:09:47
【问题描述】:
我是 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;
}
注意到这种行为,我尝试在我的类Foo 中编写一个方法Bar,定义如下:
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)
谁能向菜鸟解释这种行为?当可以手动完成时,无法在方法中使用裸词作为键是非常令人沮丧的。
【问题讨论】:
标签: javascript json bareword