简体   繁体   English

这是在javascript中调用函数的正确方法吗?

[英]Is this the right way to call a function in javascript?

This is a part of my document: 这是我的文档的一部分:

function MyFunction() {
    var x=""

    if (x=1) {
        OnBtnPbDemo_SwitchChn1(1); //This is a function
    } else {
        OnBtnPbDemo_SwitchChn1(0); //This is another function
    }
}

I want to know if this is the right way to call the functions inside the condition. 我想知道这是否是在条件内调用函数的正确方法。
Thank you very much. 非常感谢你。

是的,无论您在何处调用函数,调用函数都是相同的。

You need to use == in if condition instead use of = 您需要在if条件中使用==而不是使用=

 if (x==1) {

instead of 代替

 if (x=1) {

if you are going to call same function for the different x value, Try this 如果要为不同的x值调用相同的函数,请尝试以下操作

  function MyFunction() {
       var x = 1;   
       OnBtnPbDemo_SwitchChn1(x); //you can pass the x value directly to that function.         
    }

if you are going to call different function for the different x value, Try this 如果您要针对不同的x值调用其他函数,请尝试以下操作

  function MyFunction() {
    var x="";
        if (x==1) {
            OnBtnPbDemo_SwitchChn1(1); //This is a function
        } else {
            OnBtnPbDemo_SwitchChn1_another(0); //This is another function
        }
    }

Not entirely sure what you mean about the "right" way of calling, but you can call functions wherever as long as they're available in the scope. 不能完全确定“正确”调用方式的含义,但是只要范围内可用,就可以调用函数。

You can actually shorten what you've written to this too: 您实际上也可以缩短您为此写的内容:

function MyFunction () {
    var x = "";
    OnBtnPbDemo_SwitchChn1(x === 1 ? 1 : 0);
}

Unless you're actually changing the x variable inside your function however, it'll never run with 1 as the param. 除非您实际上在函数内部更改x变量,否则它将永远不会以1作为参数运行。

You are calling same function twice, Instead just call the function once with the value 1/0 in it. 您将调用同一函数两次,而只需使用值1/0调用一次函数。

function MyFunction() {
//Check and find value of x
if(x=="somevalue") //true condition
{
   x=1;
}
else{
x=0;
}
OnBtnPbDemo_SwitchChn1(x);
}

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

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