你怎么称呼这个 JavaScript 语法,以便我研究一下?

发布于 2024-09-08 21:35:12 字数 1818 浏览 8 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

空城之時有危險 2024-09-15 21:35:12
var gameOfLife = function() { }

函数表达式,而

function gameOfLife() { }

函数声明

引用 Juriy 'kangax' Zaytsev 关于函数表达式与函数声明的说法:

有细微的差别
声明的行为和
表达式。

首先,函数声明
在任何之前被解析和评估
其他表达方式是。即使
声明位于最后一个
来源,将被评估
首先是范围内包含的任何其他表达式
[...]

另一个
功能的重要特征
声明就是声明它们
有条件地是非标准化的并且
不同环境下有所不同。
你永远不应该依赖函数
有条件地声明并使用
相反,函数表达式。

在这种情况下,正如 Joel Coehoorn 在评论中提到的,gameOfLife 是有条件定义的,因此需要使用函数表达式。

这些条件定义函数的一般用例是增强浏览器中的 JavaScript 功能,这些浏览器不具备对新函数的本机支持(在以前的 ECMAScript/JavaScript 版本中不可用)。您不想使用函数声明来执行此操作,因为无论如何它们都会覆盖本机功能,这很可能不是您想要的(考虑到速度等)。以下是一个简短的示例

if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(item, from) {
        /* implement Array.indexOf functionality,
           but only if there's no native support */
    }
}

函数表达式的一个主要缺点是您实际上将匿名函数分配给变量。这可能会使调试更加困难,因为函数名称通常是未知的脚本执行暂停(例如,在您设置的断点处)。一些 JavaScript 调试器(例如 Firebug)尝试给出函数分配给的变量的名称,但是由于调试器必须通过动态解析脚本内容来猜测这一点,这可能太困难了(这会导致显示 (?)(),而不是函数名称)甚至是错误的。

(例如,请继续阅读页面,尽管其内容并不完全适合初学者)

var gameOfLife = function() { }

is a function expression, whereas

function gameOfLife() { }

is a function declaration.

To quote Juriy ‘kangax’ Zaytsev about Function expressions vs. Function declarations:

There’s a subtle difference in
behavior of declarations and
expressions.

First of all, function declarations
are parsed and evaluated before any
other expressions are. Even if
declaration is positioned last in a
source, it will be evaluated
foremost any other expressions contained in a scope.
[…]

Another
important trait of function
declarations is that declaring them
conditionally is non-standardized and
varies across different environments.
You should never rely on functions
being declared conditionally and use
function expressions instead.

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:

if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(item, from) {
        /* implement Array.indexOf functionality,
           but only if there's no native support */
    }
}

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)

花开雨落又逢春i 2024-09-15 21:35:12
  1. 在 JavaScript 中,函数是第一类对象。您可以将它们存储在对象(变量)中并将它们作为参数传递给函数。每个函数实际上都是一个 Function 对象。

  2. gol 是一个对象,正在使用 对象字面量表示法。

  1. 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.

  2. gol is an object, which is being initialized using the object literal notation.

一身软味 2024-09-15 21:35:12

1) 在下面的代码中,将 gameOfLive 设为变量而不仅仅是“函数 gameOfLife()”背后的原因是什么?


在全局级别定义的变量是 window 对象的成员。因此,通过将其设置为变量,您可以使用语法 window.gameOfLife()。这也是他们可以在代码片段开头使用 if (!window.gameOfLife) 检查的原因。

但这并不能真正解释为什么他们选择这样做,函数声明也会做同样的事情。 Marcel Korpel 的回答 更好地解释了这两个选项的“原因”。


2)gol是什么?它看起来像一个数组,但我不熟悉其语法或它的名称。


该语法称为紧凑对象表示法。这里有趣的是“紧凑”对象是在函数内部声明的。像这样在函数内声明对象非常有用,因为您可以使用它来构建具有(有效)私有成员的 javascript 对象。

关键是要记住 JavaScript 中的函数和对象是同一件事。因此,完整的 gameOfLife() 函数实际上是一个对象定义。此外,声明为 gameOfLife 成员的 gol 对象很可能是定义私有成员的通用技术的一部分。 gameOfLife() 函数/对象将返回此 gol 对象。在 gameOfLife() 函数/对象内声明的所有其他项目实际上都成为返回的 gol 实例的私有成员,而在 gol 内部声明的所有内容对象本身是公共的。他们真正想做的是最终编写这样的代码:

var game = new gameOfLife();

现在,当他们这样做时,游戏变量将保存一个 gol 对象。该对象中的方法仍然可以访问在完整的 gameOfLife() 函数中声明的项目,但其他代码则不能(至少不那么容易)。因此,这些项目实际上是私有的。 gol 对象本身中的项目仍然是公共的。因此,您拥有一个具有私有和公共成员的对象,用于正确的封装/信息隐藏,就像使用其他面向对象的语言构建一样。



1) In the following code, what is the reasoning behind making gameOfLive a variable and not just a "function gameOfLife()"?


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 the if (!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.


2) what is gol? It seems like an array, but I am unfamiliar with the syntax or what its called.


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, the gol object declared as a member of gameOfLife is most likely part of a common technique for defining private members. The gameOfLife() function/object will return this gol object. All other items declared inside the gameOfLife() function/object effectively become private members of the returned gol instance, while everything declared inside of the gol object itself is public. What they really want to do is eventually write code like this:

var game = new gameOfLife();

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 full gameOfLife() function, but other code does not (at least, not as easily). Thus, those items are effectively private. Items in the gol 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.


心安伴我暖 2024-09-15 21:35:12

将函数放入变量中可以让您稍后将其替换为另一个函数,从而对代码的其余部分透明地替换该函数。这与您在表单小部件上指定“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.

梦情居士 2024-09-15 21:35:12

当然:解释一下语法:

函数是 javascript 中的第一类对象,因此您可以将函数放入变量中。因此,这段代码的主要部分实际上是存储在 var gameOfLife 中的函数定义,稍后可以通过调用来使用它:

gameOfLife()

gol 是一个对象(哈希),“init”是上述语法的另一个示例,除了直接放入“gol”哈希中的“init”键。所以函数可以依次调用:

gol["init"](w,h)

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:

gameOfLife()

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:

gol["init"](w,h)
源来凯始玺欢你 2024-09-15 21:35:12

根据 此页面,在其声明中声明 gameOfLife方式与声明你的方式没有什么不同。他们定义 gol 的方式使其成为一个对象(或者您可以将其视为关联数组)。数组的一个类似的快捷方式是使用方括号而不是花括号。

According to this page, declaring gameOfLife in their way is no different from declaring it your way. The way they define gol 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.

生寂 2024-09-15 21:35:12

如果您希望函数成为对象的属性,则将函数视为变量可能会很有用。 (参见: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_))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文