当我阅读 here 的一些 Javascript 源代码 ( Conway's Game of Life ) 时,我偶然发现了一些我以前从未见过的东西(好吧,我三周前开始使用 Javascript。出于上下文考虑,我来自 C++ 背景,我使用 Professional JavaScript for Web Developers 作为尝试的指南理解 JS)
情况是这样的(fiddle):
var Obj = {
canvas: {
context : null,
init : function() {
this.canvas = document.getElementById('canvas');
this.canvas.width = 50;
this.context = this.canvas.getContext('2d');
/* ... */
}
}
}
Obj.canvas.init();
我知道这是一个具有嵌套对象文字属性的对象文字。我不明白的是 this.canvas = document.getElementById('canvas');
部分。我以为我需要声明一个变量,例如上面声明的 context
来获取 Canvas 元素。
这显然有效,正如 fiddle 上所述,但是,这是怎么回事?更准确地说,通过使 canvas 成为 HTML 元素对象,为什么我不会丢失它的所有其他属性,例如 context
?
最佳答案
这里有两个不同的对象称为“ Canvas ”。一个是Obj
的成员,另一个是Obj.canvas
的成员。 Obj.canvas
是一个通用对象,Obj.canvas.canvas
是一个 HTML 元素。当您在“init”行之后添加 console.dir(Obj)
时,您会看到这一点。
这样命名是否是一个好的做法是另一个问题。我宁愿这样写:
var Obj = {
canvas: {
context : null,
element: null,
init : function() {
this.element = document.getElementById('canvas');
this.element.width = 50;
this.context = this.element.getContext('2d');
etc.
关于javascript - 对嵌套对象文字属性感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21282632/