下面的函数调用在 Javascript 中是如何工作的

发布于 2024-11-18 06:59:31 字数 1214 浏览 2 评论 0原文

我一直在使用与这真的很酷 文章。

在文章代码中,变量被分配了一个函数,如下所示:

var messageFactory = (function() {
    var that = {},
        $chatMessage = $('<p></p>').
          addClass('chat message'),
        $nick = $('<span></span>').
          addClass('nick'),
        $systemMessage = $('<p></p>').
          addClass('system message');

    var chat = function(message) {
      var $filledNick = $nick.clone().
            text(message.nick + ':');
      return $chatMessage.clone().
        append($filledNick).
        append(message.text);
    };

    var system = function(message) {
      return $systemMessage.clone().text(message.text);
    };

    that.chat = chat;
    that.system = system;

    return that;
  })();

稍后调用子函数,如下所示

messageFactory.system({ text: 'You changed your nick to ' + nick + '.'})

messageFactory.chat({ nick: 'me', text: message })

这些调用中发生了什么?具体来说,var messageFactory 的工作方式与 C# 等语言中的类定义类似,并且我缺少与范围相关的机制来了解如何通过对象 { text: '...' ...} 传递值。

非常感谢!

I've been playing with the code associated with this really cool article.

In the articles code a variable is assigned a function as follows:

var messageFactory = (function() {
    var that = {},
        $chatMessage = $('<p></p>').
          addClass('chat message'),
        $nick = $('<span></span>').
          addClass('nick'),
        $systemMessage = $('<p></p>').
          addClass('system message');

    var chat = function(message) {
      var $filledNick = $nick.clone().
            text(message.nick + ':');
      return $chatMessage.clone().
        append($filledNick).
        append(message.text);
    };

    var system = function(message) {
      return $systemMessage.clone().text(message.text);
    };

    that.chat = chat;
    that.system = system;

    return that;
  })();

Later sub functions are called like the following,

messageFactory.system({ text: 'You changed your nick to ' + nick + '.'})

and

messageFactory.chat({ nick: 'me', text: message })

What's going on in those calls? Specifically it appears that the var messageFactory is working similar to a class definition in language like C#, and I'm missing the scope related mechanisms to how the values are being passed via the object { text: '...' ...}.

Thanks much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

冧九 2024-11-25 06:59:31

首先要注意的也是最重要的事情是最后一行。具体来说,是 ; 之前的 ()。它所做的就是立即执行第 1 行的匿名函数。值得注意的是,messageFactory 不会包含匿名函数,而是包含它返回的任何内容。为了更好地理解这一点,我将举一个例子...

var x = (function(){ return "Hello!"; })();
// x will contain "Hello!", not the function.

第二件事要记住的是,Javascript 中的对象将维护对创建它们的闭包的引用。因此,如果您立即执行像我们这样的函数执行上述操作后,这将形成一个闭包,并且即使在函数执行完毕后,在该闭包中创建的对象也将保留对其的引用。另一个例子......

var sayHi = (function(){ 
    var salutation = "Hello";
    return function(name) {
       return salutation + ", " + name + ".";
    }
})();

再次注意,我们有一个立即执行的匿名函数。因此变量 sayHi 将不包含外部匿名函数,而是包含返回值。所以 sayHi 实际上会包含 function(name){ return salutation + ", " + name + ".";}。您会注意到,我们没有传入 salutation,但我们仍然可以访问它,因为它是创建此函数的 closure 的一部分

。理解所提供的代码是在 Javascript 中,{} 是一个对象字面量。它本质上相当于 new Object()。这些对象可以具有与 C# 对象相同的属性和方法,这就是您所引用的 .text 的来源。

第 2 行,代码创建一个对象字面量:var that = {}。下一个 var 创建是 var chat = function(message){....,其中创建了一个函数,该函数接受一个 message 参数并用它做一些事情。在代码末尾,该 chat 函数被分配给 thatchat 属性,然后分配给 that返回:that.chat = chat返回该

所有这一切的要点是 messageFactory 不包含它似乎分配给的函数,而是包含该函数的 return 。在本例中,该返回实际上是 that 对象,它具有 chatsystem 两个属性。这些属性实际上指向创建 that 的同一个闭包内的 chatsystem 变量,这使得这一切都有效。

最后一部分很简单......当您调用 messageFactory.chat({ text: 'something', nick:Joe}) 时,您实际上传递了一个 < code>Object 作为闭包内 chat 函数的参数。然后,它引用对象的 nicktext 属性来返回其结果。

希望有帮助。我不确定我是否解释得很好,但这就是它在我脑海中的运作方式。

The first and arguably most important thing to note is the last line. Specifically, the () before the ;. What this is doing is immediately executing the anonymous function on line 1. This is important to note because messageFactory will not contain the anonymous function, but rather whatever is returned from it. To better understand that, I'll give an example...

var x = (function(){ return "Hello!"; })();
// x will contain "Hello!", not the function.

The second thing to keep in mind is that objects in Javascript will maintain a reference to the closure that they were created in. So if you immediately execute a function like we're doing above, that will a form a closure and objects created in that closure will maintain a reference to it even after the function is done executing. Another example....

var sayHi = (function(){ 
    var salutation = "Hello";
    return function(name) {
       return salutation + ", " + name + ".";
    }
})();

Note again that we have an anonymous function being immediately executed. So the variable sayHi will not contain the outside anonymous function, but rather it's return value. So sayHi will actually contain function(name){ return salutation + ", " + name + ".";}. You'll note that we're not passing in salutation, but we can still access it as it's part of the closure that this function was created in.

The final thing to understand the provided code is that in Javascript, {} is an Object literal. It's essentially equivalent to saying new Object(). These objects can have properties and methods the same as a C# object, which is where the .text is coming from that you referred to.

On line 2, the code is creating an Object literal: var that = {}. The next var creation is var chat = function(message){.... where a function is created which takes a message parameter and does some stuff with it. Towards the end of the code, that chat function is then assigned to the chat property of that and then that is returned: that.chat = chat and return that.

The point of all this is that messageFactory does not contain the function it appears to be assigned to, but rather the return of that function. In this case, that return is actually the that Object, which has two properties of chat and system. Those properties actually point back to the chat and system variables inside the same closure that that was created in, which makes this all work.

The final piece is simple enough.... when you call messageFactory.chat({ text: 'something', nick:Joe}) you're actually passing an Object as a parameter to the chat function inside the closure. It then references the object's nick and text properties to return its result.

Hope that helps. I'm not sure I explained it very well, but that's kind of how it works in my head.

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