简体   繁体   English

在函数内部设置javascript参数

[英]Set javascript parameter inside function

How to set variable which I pass to a function 如何设置传递给函数的变量

function checkSetName(inputVar, outputVar, txt){
            if (inputVar.length) {
                outputVar = txt + ': ' + inputVar.val();
            } else {
                outputVar = "";
            }
        }
checkSetName(name, nameTxt, 'Hello world ');

I pass the empty variable nameTxt and I expect it to be set the value inside of function, but after function executes the variable is undefined 我传递了空变量nameTxt,并希望将其设置为函数内部的值,但是函数执行后,该变量undefined

How to set variable that I pass to a function in JavaScript 如何在JavaScript中设置传递给函数的变量

You can't because JS is a strictly pass-by-value language, there are no ByRef parameters. 您不能因为JS是严格的按值传递语言,所以没有ByRef参数。 Just return a value. 只需返回一个值。

function checkSetName(inputVar, txt){
        if (inputVar.length) {
            return txt + ': ' + inputVar.val();
        } else {
            return  = "";
        }

Another (worse) option is to pass an object and modify its state: 另一个(更糟糕的)选择是传递对象并修改其状态:

function checkSetName(inputVar, state, txt){
        if (inputVar.length) {
            state.output = txt + ': ' + inputVar.val();
        } else {
            state.output = "";
        }

Finally, you can make your a function a method and modify this instead of a parameter object: 最后,您可以使函数成为方法并修改this而不是参数对象:

class Validations {
    checkSetName(inputVar, txt){
        if (inputVar.length) {
            this.output = txt + ': ' + inputVar.val();
        } else {
            this.output = "";
        }
}

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

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