简体   繁体   中英

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 (x==1) {

instead of

 if (x=1) {

if you are going to call same function for the different x value, Try this

  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

  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.

You are calling same function twice, Instead just call the function once with the value 1/0 in it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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