所以,我一头扎进了 Marijn Haverbeke 的 Eloquent Javascript 中。直接游到Electronic Life章。
在那里我们观察到一个物体的自发生成:
{"#": Wall,"o": BouncingCritter}
Wall 和 BouncingCritter 的定义如下:
function Wall() {}
function BouncingCritter() {
this.direction = randomElement(directionNames);
this.name = word();
};
BouncingCritter.prototype.act = function(view) {
if (view.look(this.direction) != " ")
this.direction = view.find(" ") || "s";
return {type: "move", direction: this.direction};
};
BouncingCritter.prototype.toString=function(){
return this.name +"\t"+ this.direction;
}
---> 我不明白那里发生了什么巫术。 嗯,我看到我们正在动态创建一个对象,并且由于它只会使用一次,因此不需要定义类。好的。 据我所知,到目前为止,这个匿名对象有两个属性,它们本身就是类,它们将在以后多次实例化。我开始心慌意乱,但我会相处的。其中之一(Wall)是相当空的,稍后将被证明是有用的,因为“什么都没有”比“未定义”要好一些。很好。
我不明白的是在冒号左侧使用字符串常量“#”和“o”。有人可以详细说明一下吗?
衷心感谢,
最佳答案
What I don't get is the use of string constants "#" and "o" on the left hand side of the colon. Could someone please expand on this ?
该属性必须被称为某物。这些只是毫无帮助的名称,无法告诉您该属性(property)实际拥有什么。
...直到你查看上下文。从您提供的链接:
The “#” characters in this plan represent walls and rocks, and the “o” characters represent critters.
它使用 #
作为墙属性的名称,因为这是用于在 UI 中呈现它的符号。同上“o”/citter。
(不过,这仍然不是一个好名字:它将内部名称与其表示形式紧密结合在一起,如果后来将 UI 更改为使用(例如)漂亮的图形而不是 ASCII 艺术,那么它就会开始崩溃)
关于javascript - 速记符号中的无类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30833438/