尝试将字符串传递给构造函数

时间:2020-05-31 21:58:38

标签: javascript jquery

在理解功能的过程中,

仍然徘徊。我该如何使用要传递的值构造一个函数?

var box = $('#box1');


function pushCard(arg1) {
  if (this.style.opacity == 0.5) {
    this.style.opacity = 1;
  } 
  else {
    this.style.opacity = 0.5;
    window.alert(arg1);
  }
}

box.click(pushCard('String'));

1 个答案:

答案 0 :(得分:1)

tl; dr :请注意函数/函数结果之间的区别以及何时将函数作为值传递/何时调用(以及传递结果)

罪魁祸首是这一行:

box.click(pushCard('String'));

您正在用“某物”呼叫box.click()。 JavaScript需要在将表达式作为函数参数传递之前对其求值。

在这种情况下,您指示JavaScrip运行box.click(pushCard('String')) =以值为box.click作为第一个参数调用pushCard('String')

为此,JavaScript首先需要通过以值pushCard('String')作为第一个参数运行pushCard来评估'String'(这不需要更多的评估,因为它已经是一个值)

pushCard('String')的结果为undefined(您未从该函数返回任何内容)。因此,实际上相当于box.click(undefined)

这就是您想要的:

box.click(function() {pushCard('String')});

(或带有ES6箭头功能:box.click(() => pushCard('String'));

在这种情况下,您要为box.click()分配一个功能。这就是jQuery .click()所期望的,单击处理程序将运行(被评估)然后发生单击,而不是在分配了单击处理程序时发生。

在JavaScript中,您可以将函数作为值传递,并且在明确地称为时对它们进行评估:

function test() {
   alert('I have been called');
}

function delay_it(handler) {
   setTimeout(function() {
      handler(); // ⇽ call given function
   }, 1000);
   // shorter: setTimeout(handler, 1000);
}

// Wrong (we're calling test() by ourselves and passing the result (undefined) to delay_it
delay_it(test());

// Correct (we're giving test as function to delay_it, delay_it will call the function)
delay_it(test);