修改函数内的变量 [英] Modify a variable inside a function

查看:81
本文介绍了修改函数内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Lets say I have an inline script tag that has a very simple code as follows

(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"

 })();

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

However if i use test = modifyTest(test); the change is applied my question is this. Is this the only way to modify a variable in javascript inside a function, meaning i must always do

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

source = function(source); inorder to alter a variable inside a function,

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

or am i missing a scope concept that is preventing me from accomplishing this?

推荐答案

modifyTest 函数实质上是创建一个名为的本地函数级变量取值;该变量仅存在于函数范围内,因此修改它不会影响外部作用域。

The modifyTest function is essentially creating a local, function-level variable called s; that variable only exists within the scope of the function, so modifying it will not effect external scope.

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

If you want to modify the external scope, you would not use an argument:

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

不是说你可以修改通过引用传递的对象,所以你可以修改某些属性:

Not that you can modify an object passed by reference, so you can modify something's properties:

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

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

You could even pass in the name of the property you wish to modify:

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

这篇关于修改函数内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆