修改函数内的变量

Mou*_*oot 7 javascript function

假设我有一个内联脚本标记,其代码非常简单,如下所示

(function() {
 var test = "This is a simple test";

 function modifyTest(s) {
  s = "Modified test text";
 };

 modifyTest(test);
 console.log(test) //Will still display "This is a simple test"

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

但是,如果我使用test = modifyTest(test); 更改应用我的问题是这个.这是在函数内部修改javascript变量的唯一方法,这意味着我必须始终这样做

source = function(source); 为了改变函数内部的变量,

或者我错过了阻碍我完成此操作的范围概念?

Eth*_*own 14

该modifyTest函数实际上是创建一个名为的本地函数级变量s; 该变量仅存在于函数范围内,因此修改它不会影响外部范围.

如果要修改外部作用域,则不使用参数:

var test = "This is a simple test";
function modifyTest(){
    test = "modified test text";
}
console.log(test);   // This is a simple test
modifyTest();
console.log(test);   // Modified test text
Run Code Online (Sandbox Code Playgroud)

并不是说您可以修改通过引用传递的对象,因此您可以修改某些属性:

var o = { test: 'This is a simple test' };
function modifyTest(x){
    x.test = 'modified test text';
}
modifyTest(o);
console.log(o.test);   // modified test text
Run Code Online (Sandbox Code Playgroud)

您甚至可以传递要修改的属性的名称:

var o = { test: 'This is a simple test' };
function modifyTest(x, name){
    x[name] = 'modified test text';
}
modifyTest(o, 'test');
console.log(o.test);    // modified test text
Run Code Online (Sandbox Code Playgroud)


Joh*_* H. 5

您正在谈论“按引用”调用函数。JavaScript(与大多数其他函数式语言一样)不支持这一点,因为更改当前范围之外的变量是一种副作用,并且与函数式编程范式相矛盾。

不过,您始终可以更改当前范围内的变量。因此,在另一个函数中定义的任何函数都可以更改外部函数的任何局部变量。