需要的功能和不需要的变量

jol*_*olt 3 javascript function

在PHP中我们可以在函数中指定变量的默认值,如:

function myFunction(myDefaultVariable, myOtherVariable, myCheckVariable = "basic"){
    // so yeah, myDefaultVariable is required always,
    // same applies for myOtherVariable,
    // and myCheckVariable can be skipped in function call, because it has a default value already specified.
}
Run Code Online (Sandbox Code Playgroud)

在JavaScript中有类似的东西吗?

Mic*_*ins 9

您不需要在Javascript中传递所有变量.

虽然使用对象的方法不那么简单:

function foo(args) {
    var text = args.text || 'Bar';

    alert(text);
}
Run Code Online (Sandbox Code Playgroud)

打电话给它:

foo({ text: 'Hello' }); // will alert "Hello"
foo(); // will alert "Bar" as it was assigned if args.text was null
Run Code Online (Sandbox Code Playgroud)