你怎么称呼这个 JavaScript 语法,以便我研究一下?
1) 在下面的代码中,将 gameOfLive
设为变量而不仅仅是 function gameOfLife()
的原因是什么?
2)什么是gol
?它看起来像一个数组,但我不熟悉其语法或它的名称。
我正在学习 http://sixfoottallrabbit.co.uk/gameoflife/
if (!window.gameOfLife) var gameOfLife = function() {
var gol = {
body: null,
canvas: null,
context: null,
grids: [],
mouseDown: false,
interval: null,
control: null,
moving: -1,
clickToGive: -1,
table: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(''),
tableBack: null,
init: function(width, height) {
gol.body = document.getElementsByTagName('body')[0];
gol.canvas = document.createElement('canvas');
if (gol.canvas.getContext) {
gol.context = gol.canvas.getContext('2d');
document.getElementById('content').appendChild(gol.canvas);
gol.canvas.width = width;
gol.canvas.height = height;
gol.canvas.style.marginLeft = "8px";
gol.control = document.getElementById('gridcontrol');
gol.canvas.onmousedown = gol.onMouseDown;
gol.canvas.onmousemove = gol.onMouseMove;
gol.canvas.onmouseup = gol.onMouseUp;
gol.addGrid(48,32,100,44,8);
gol.refreshAll();
gol.refreshGridSelect(-1);
gol.getOptions(-1);
gol.genTableBack();
} else {
alert("Canvas not supported by your browser. Why don't you try Firefox or Chrome? For now, you can have a hug. *hug*");
}
},
}
}
1) In the following code, what is the reasoning behind making gameOfLive
a variable and not just function gameOfLife()
?
2) What is gol
? It seems like an array, but I am unfamiliar with the syntax or what its called.
I am studying http://sixfoottallrabbit.co.uk/gameoflife/
if (!window.gameOfLife) var gameOfLife = function() {
var gol = {
body: null,
canvas: null,
context: null,
grids: [],
mouseDown: false,
interval: null,
control: null,
moving: -1,
clickToGive: -1,
table: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(''),
tableBack: null,
init: function(width, height) {
gol.body = document.getElementsByTagName('body')[0];
gol.canvas = document.createElement('canvas');
if (gol.canvas.getContext) {
gol.context = gol.canvas.getContext('2d');
document.getElementById('content').appendChild(gol.canvas);
gol.canvas.width = width;
gol.canvas.height = height;
gol.canvas.style.marginLeft = "8px";
gol.control = document.getElementById('gridcontrol');
gol.canvas.onmousedown = gol.onMouseDown;
gol.canvas.onmousemove = gol.onMouseMove;
gol.canvas.onmouseup = gol.onMouseUp;
gol.addGrid(48,32,100,44,8);
gol.refreshAll();
gol.refreshGridSelect(-1);
gol.getOptions(-1);
gol.genTableBack();
} else {
alert("Canvas not supported by your browser. Why don't you try Firefox or Chrome? For now, you can have a hug. *hug*");
}
},
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
是函数表达式,而
是函数声明。
引用 Juriy 'kangax' Zaytsev 关于函数表达式与函数声明的说法:
在这种情况下,正如 Joel Coehoorn 在评论中提到的,gameOfLife 是有条件定义的,因此需要使用函数表达式。
这些条件定义函数的一般用例是增强浏览器中的 JavaScript 功能,这些浏览器不具备对新函数的本机支持(在以前的 ECMAScript/JavaScript 版本中不可用)。您不想使用函数声明来执行此操作,因为无论如何它们都会覆盖本机功能,这很可能不是您想要的(考虑到速度等)。以下是一个简短的示例:
函数表达式的一个主要缺点是您实际上将匿名函数分配给变量。这可能会使调试更加困难,因为函数名称通常是未知的脚本执行暂停(例如,在您设置的断点处)。一些 JavaScript 调试器(例如 Firebug)尝试给出函数分配给的变量的名称,但是由于调试器必须通过动态解析脚本内容来猜测这一点,这可能太困难了(这会导致显示
(?)()
,而不是函数名称)甚至是错误的。(例如,请继续阅读页面,尽管其内容并不完全适合初学者)
is a function expression, whereas
is a function declaration.
To quote Juriy ‘kangax’ Zaytsev about Function expressions vs. Function declarations:
In this case, as Joel Coehoorn mentions in a comment,
gameOfLife
is defined conditionally, so it's needed to use a function expression.A general use case for these conditionally defined functions is to enhance JavaScript functionality in browsers that don't have native support for newer functions (not available in previous ECMAScript/JavaScript versions). You don't want to do this using function declarations, as those will overwrite the native functionality anyway, which is most likely not what you want (considering speed, etc.). A short example of this:
One major drawback of function expressions is that you in fact assign an anonymous function to a variable. This can make debugging harder, as the function name is usually not known when script execution halts (e.g., on a breakpoint you set). Some JavaScript debuggers, like Firebug, try to give the name of the variable the function was assigned to, but as the debugger has to guess this by parsing the script contents on-the-fly, this can be too difficult (which results in a
(?)()
being shown, instead of a function name) or even be wrong.(for examples, read on on the page, though its contents are not entirely suitable for beginners)
在 JavaScript 中,函数是第一类对象。您可以将它们存储在对象(变量)中并将它们作为参数传递给函数。每个函数实际上都是一个
Function
对象。gol
是一个对象,正在使用 对象字面量表示法。In JavaScript, functions are first class objects. You could store them in objects (variables) and pass them as arguments to functions. Every function is actually a
Function
object.gol
is an object, which is being initialized using the object literal notation.在全局级别定义的变量是 window 对象的成员。因此,通过将其设置为变量,您可以使用语法
window.gameOfLife()
。这也是他们可以在代码片段开头使用if (!window.gameOfLife)
检查的原因。但这并不能真正解释为什么他们选择这样做,函数声明也会做同样的事情。 Marcel Korpel 的回答 更好地解释了这两个选项的“原因”。
该语法称为紧凑对象表示法。这里有趣的是“紧凑”对象是在函数内部声明的。像这样在函数内声明对象非常有用,因为您可以使用它来构建具有(有效)私有成员的 javascript 对象。
关键是要记住 JavaScript 中的函数和对象是同一件事。因此,完整的
gameOfLife()
函数实际上是一个对象定义。此外,声明为gameOfLife
成员的gol
对象很可能是定义私有成员的通用技术的一部分。gameOfLife()
函数/对象将返回此gol
对象。在gameOfLife()
函数/对象内声明的所有其他项目实际上都成为返回的gol
实例的私有成员,而在gol
内部声明的所有内容对象本身是公共的。他们真正想做的是最终编写这样的代码:现在,当他们这样做时,游戏变量将保存一个
gol
对象。该对象中的方法仍然可以访问在完整的gameOfLife()
函数中声明的项目,但其他代码则不能(至少不那么容易)。因此,这些项目实际上是私有的。gol
对象本身中的项目仍然是公共的。因此,您拥有一个具有私有和公共成员的对象,用于正确的封装/信息隐藏,就像使用其他面向对象的语言构建一样。Variables defined at the global level are members of the window object. So by making it a variable, you make it possible to use the syntax
window.gameOfLife()
. That's also why they can use theif (!window.gameOfLife)
check at the beginning of your snippet.But that doesn't really explain why they chose to do it this way, and a function declaration would do the same thing. Marcel Korpel's answer better explains the "why" of the two options.
The syntax is called compact object notation. What makes it interesting here is that the "compact" object is declared inside a function. Declaring an object inside a function like this is useful because you can use it to build javascript objects with (effectively) private members.
The key is to remember that functions and objects in javascript are the same thing. Thus, the full
gameOfLife()
function is really an object definition. Furthermore, thegol
object declared as a member ofgameOfLife
is most likely part of a common technique for defining private members. ThegameOfLife()
function/object will return thisgol
object. All other items declared inside thegameOfLife()
function/object effectively become private members of the returnedgol
instance, while everything declared inside of thegol
object itself is public. What they really want to do is eventually write code like this:Now, when they do that, the game variable will hold a
gol
object. The methods in this object still have access to items declared in the fullgameOfLife()
function, but other code does not (at least, not as easily). Thus, those items are effectively private. Items in thegol
object itself are still public. Thus you have an object with both private and public members for proper encapsulation/information hiding, just like you'd build with other object-oriented languages.将函数放入变量中可以让您稍后将其替换为另一个函数,从而对代码的其余部分透明地替换该函数。这与您在表单小部件上指定“onClick=”时所做的操作相同。
Putting a function in a variable allows you to come along later and replace it with another function, replacing the function transparently to the rest of your code. This is the same thing you're doing when you specify "onClick=" on a form widget.
当然:解释一下语法:
函数是 javascript 中的第一类对象,因此您可以将函数放入变量中。因此,这段代码的主要部分实际上是存储在 var gameOfLife 中的函数定义,稍后可以通过调用来使用它:
gol 是一个对象(哈希),“init”是上述语法的另一个示例,除了直接放入“gol”哈希中的“init”键。所以该函数可以依次调用:
sure: to explain the syntax:
functions are first class objects in javascript, so you can put a function into a variable. thus the main part of this code is in fact a function definition stored in var gameOfLife, which could later be used by calling:
gol is an object (hash), and "init" is another example of the above syntax, except put directly into the "init" key in the "gol" hash. so that function in turn could be called by:
根据 此页面,在其声明中声明
gameOfLife
方式与声明你的方式没有什么不同。他们定义 gol 的方式使其成为一个对象(或者您可以将其视为关联数组)。数组的一个类似的快捷方式是使用方括号而不是花括号。According to this page, declaring
gameOfLife
in their way is no different from declaring it your way. The way they definegol
makes it an object (or you can think of it as an associative array). A similar shortcut for arrays is to use square brackets instead of curly braces.如果您希望函数成为对象的属性,则将函数视为变量可能会很有用。 (参见:http://www.permadi.com/tutorial/jsFunc/index.html )
我相信 gol 是一个以名称/值对描述的 JavaScript 对象——很像 JSON 格式。 (参见:http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_))
Considering a function as a variable may be useful if you would like a function to be a property of an Object. (See: http://www.permadi.com/tutorial/jsFunc/index.html)
I believe gol is a JavaScript object described in name/value pairs -- much like the JSON format. (See: http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_))