函数如何在push方法内部工作?

huangapple go评论72阅读模式
英文:

How does a function work inside the push method?

问题

  1. 关于 var Webflow = Webflow || [];,将变量设置为带有空数组的OR运算符的目的是什么?

  2. 关于随后的push方法(Webflow.push(function() {...),在push方法内部创建函数的方式是如何/为什么要这样做的?我理解push方法用于向数组添加项目,但我在网上找不到关于在push方法内部创建函数的工作原理的信息。这是否最终会使原始变量“Webflow = Webflow OR [最终函数的结果]”?

希望我的问题足够清晰。任何洞察力或清晰度,即使不直接回答我的问题,都将有所帮助。我的目标是完全理解这段代码的每一行。谢谢!🙏

<script>
var Webflow = Webflow || [];
Webflow.push(function () {
  var l = $(".w-slider-arrow-left");
  var r = $(".w-slider-arrow-right");
  $("#flowbaseSlider1")
    .on("click", ".back-button", function () {
      l.trigger("tap");
    })
    .on("click", ".next-button", function () {
      r.trigger("tap");
    });
});
</script>

我一直在Google上搜索代码的各个方面,以便全面理解它。

英文:

I have 2 questions.

  1. Regarding var Webflow = Webflow || [];, what is the purpose of setting the variable to have the OR operator with a blank array?

  2. Regarding the push method that follows ( Webflow.push(function() {...), how/why is there a function created inside the push method. I understand the push method is used to add items to an array, but I can't find much info online about how it works when you put create a function inside the push method. Does it ultimately make the original variable "Webflow = Webflow OR [result of the final function]?

I hope my questions are clear enough. Any insight or clarity, even if it doesn't directly answer my questions would be helpful. My goal is to fully understand every line of this code. Thank you! 🙏

&lt;script&gt;
var Webflow = Webflow || [];
Webflow.push(function () {
  var l = $(&quot;#flowbaseSlider1 .w-slider-arrow-left&quot;);
  var r = $(&quot;#flowbaseSlider1 .w-slider-arrow-right&quot;);
  $(&quot;#flowbaseSlider1&quot;)
    .on(&quot;click&quot;, &quot;.back-button&quot;, function () {
      l.trigger(&quot;tap&quot;);
    })
    .on(&quot;click&quot;, &quot;.next-button&quot;, function () {
      r.trigger(&quot;tap&quot;);
    });
});
&lt;/script&gt;

I've been Googling each aspect of the code to fully understand it.

答案1

得分: 1

  1. 否则会抛出错误 - TypeError: 无法读取未定义的属性推送

  2. 你可以将一个函数推入一个数组中。如果你这样做,数组将只保留函数的引用。

const someFunction = function() { return 5 }

const array = []
array.push(someFunction)

console.log(array[0])

const value = array[0]()
console.log(value)

它最终是否使原始变量 "Webflow = Webflow OR [最终函数的结果]"?

不,没有任何奇迹发生,只是数组里面有一个函数。

英文:
  1. It would throw an error - TypeError: Cannot read property push of undefined otherwise

  2. You can push a function into an array. If you do that the array will just hold the function reference.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const someFunction = function() { return 5 }

const array = []
array.push(someFunction)

console.log(array[0])

const value = array[0]()
console.log(value)

<!-- end snippet -->

> Does it ultimately make the original variable "Webflow = Webflow OR [result of the final function]?

No, no magic happens, just a function inside an array

答案2

得分: 0

以下是您问题中代码的翻译:


以下是一些更多的元素,以便完全理解您问题中的代码...

var Webflow = Webflow || []

这基本上是一个带有短路求值变量声明。在这种情况下,我们有一个逻辑或表达式 (Webflow || []),这要归功于**||运算符**(参见 Logical OR (||) - JavaScript | MDN)。这就是布尔运算的魔力所在... 这是什么意思呢?如果 Webflow 是一个真值,那么 var Webflow = Webflow。否则,var Webflow = []

值得一提的是,这种语法在ES5项目中经常用于在函数内获取默认参数,因为它非常方便:

function somebody(username) {
  username = username || 'Badacadabra';
  console.log(username);
}

somebody();

我们也可以这样写...

function somebody(username) {
  if (!username) {
    username = 'Badacadabra';
  }

  console.log(username);
}

somebody();

... 或者像这样(这比较繁琐):

function somebody(username) {
  username = username ? username : 'Badacadabra';
  console.log(username);
}

somebody();

在上面的代码中,由于我在调用 somebody() 函数时没有传递任何参数,所以 username 首先是 undefined。但是 undefined 是一个假值,因此在使用 || 运算符的布尔上下文中,username 变成了 'Badacadabra'。我调用函数如下也会得到相同的结果:

somebody(false); // Badacadabra
somebody(''); // Badacadabra
somebody(null); // Badacadabra
somebody(0); // Badacadabra
// ...

然而,如果我传递一个真值,它将被保留:

somebody('Jedd Soh'); // Jedd Soh

ES6引入了更容易使用的默认参数

function somebody(username = 'Badacadabra') {
  console.log(username);
}

Webflow.push(function() {})

JavaScript 是一种非常灵活的语言,在许多不同的情况下都可以找到函数:包括自调用的函数、与对象文字中的键关联的函数、嵌套在其他函数中的函数,当然还有在数组中的函数...

因此,在 JavaScript 中,当您想要创建一个新函数时,有几个选项。但我认为我们可以说有两个主要概念(因为通过 Function 构造函数显式定义函数并不推荐):

  1. 函数声明
  2. 函数表达式

一方面,function somebody() {} 是一个函数声明(或语句)。另一方面,var somebody = function() {}; 是一个将 somebody 作为变量名并分配一个匿名函数函数表达式。函数表达式也可以命名,尤其是用于递归。它有时会在 IIFEs 中使用。

一个数组可以包含字符串或数字,还可以包含数组、对象文字和... 函数(它们是Function对象)。如果我打印 somebody.constructor === Function;,它将返回 true。因此,是的,您可以使用 Array.prototype.push() 推送函数。

var arr = [];

arr.push(function () {
  console.log('Hello');
});

arr.push(function () {
  console.log('World');
});

arr[0](); // Hello
arr[1](); // World

英文:

Here are some more elements to fully understand the code in your question...

var Webflow = Webflow || []

This is basically a variable declaration with a short-circuit evaluation. In this case, we have a logical OR expression (Webflow || []) thanks to the use of the || operator (see Logical OR (||) - JavaScript | MDN). This is where the magic of boolean operations comes into play... What does that mean? If Webflow is a truthy value, then var Webflow = Webflow. Otherwise, var Webflow = [].

For the record, this syntax was often used in ES5 projects to get default parameters within functions because it is quite handy:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function somebody(username) {
  username = username || &#39;Badacadabra&#39;;
  console.log(username);
}

somebody();

<!-- end snippet -->

We could also write something like this...

function somebody(username) {
  if (!username) {
    username = &#39;Badacadabra&#39;;
  }

  console.log(username);
}

somebody();

... or like that (which is cumbersome):

function somebody(username) {
  username = username ? username : &#39;Badacadabra&#39;;
  console.log(username);
}

somebody();

In the above code, since I do not pass any argument when I call my somebody() function, username is, at first, undefined. But undefined is a falsy value, so in the boolean context where the || operator is used, username becomes &#39;Badacadabra&#39;. I would get the same result calling my function like so:

somebody(false); // Badacadabra
somebody(&#39;&#39;); // Badacadabra
somebody(null); // Badacadabra
somebody(0); // Badacadabra
// ...

However, if I put a truthy value in there, it will be kept:

somebody(&#39;Jedd Soh&#39;); // Jedd Soh

ES6 introduced default parameters that you can use more easily now:

function somebody(username = &#39;Badacadabra&#39;) {
  console.log(username);
}

Webflow.push(function() {})

JavaScript is a very flexible language where you can find functions in many different situations: functions which call themselves, functions associated with keys in object literals, functions inside other functions, and of course, functions in arrays...

So, in JavaScript, you have several options when you want to create a new function. But I think we can say that there are two main concepts (because defining a function through the Function constructor explicitly is not recommended):

  1. Function declaration
  2. Function expression

On the one hand, function somebody() {} is a function declaration (or statement). On the other hand, var somebody = function() {}; is a function expression with somebody as the variable name and an anonymous function assigned. A function expression could be named too, especially for recursion. It is sometimes used in IIFEs.

An array may contain strings or numbers, but also arrays, object literals and... functions (which are Function objects). If I print somebody.constructor === Function;, it will return true. Therefore, yes, you can push functions with Array.prototype.push().

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr = [];

arr.push(function () {
  console.log(&#39;Hello&#39;);
});

arr.push(function () {
  console.log(&#39;World&#39;);
});

arr[0](); // Hello
arr[1](); // World

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月9日 00:08:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定