简体   繁体   English

Javascript function 语法需要解释

[英]Javascript function syntax needs explanation

return this.foo("abc",function(){
                           //do something
                      });

Can some one tell me what does the above line do?有人可以告诉我上面的行是做什么的吗? THanks谢谢

It calls the function referenced by this.foo and passes two parameters: The string "abc" and an anonymous function function(){ //do something} .它调用 this.foo 引用的this.foo并传递两个参数: 字符串"abc"和匿名function function(){ //do something} It then return s the result.然后它return结果。

It is equivalent to:它相当于:

var a = "abc";
var b = function(){ 
    //do something
};
return this.foo(a, b);

Functions are first class objects in JS so you can pass them around like any other value.函数首先是 JS 中的 class 对象,因此您可以像传递任何其他值一样传递它们。


I recommend to have a look at the MDC JavaScript guide .我建议查看MDC JavaScript 指南

  1. It grabs a reference to this , which might be the DOM Window, a DOM element, or any other JavaScript object depending on how and where the above code is being run.它获取this的引用,这可能是 DOM Window、DOM 元素或任何其他 JavaScript object,具体取决于上述代码的运行方式和位置。
  2. It (skipping ahead) prepares a new anonymous Function that //does something .它(跳过)准备了一个新的匿名Function //does something
  3. It attempts to invoke a method foo on object this , passing in two parameters "abc" and said anonymous Function .它试图在 object this上调用foo方法,传入两个参数"abc"并表示匿名Function

Very often when you see code that passes along an anonymous function (eg function(){... } ), it is in fact holding on to that function in order to execute it not right away but at some later point in time, such as in response to a click event or a timer.很多时候,当您看到通过匿名 function (例如function(){... } )传递的代码时,实际上是坚持使用 function 以便不是立即执行它,而是在稍后的某个时间点执行它,例如如响应点击事件或计时器。

looks like this.foo() is a function that returns something.看起来 this.foo() 是一个返回一些东西的 function 。 so the return value is, what this.foo() returns.所以返回值是 this.foo() 返回的值。

calls an instance method that gets as parameters a string and a function.调用一个实例方法,该方法获取一个字符串和一个 function 作为参数。

It will return (yeah, like it is in English) the returned result of a function this.foo(...) (in the most simple form, ithe function this.foo(...) return "something" then the code will return "something").它将返回(是的,就像英文一样) function this.foo(...)的返回结果(以最简单的形式,即 function this.foo(...)返回“某物”然后代码将返回“某物”)。 The function this.foo("abc", function(){...}); function this.foo("abc", function(){...}); is itself a function which receives 2 arguments: A string "abc" and a function().本身就是一个 function,它接收 2 个 arguments:一个字符串“abc”和一个函数()。 The function this.foo will do something and return "something" to return by the main function. function this.foo 将做某事并返回“某事”以由主 function 返回。 [x] [X]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM