Change the variable inside the function

Let's say I have a built-in script tag that has very simple code, as shown below.

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

 })();

However, if I use the test = modifyTest(test); change applied, my question is this. This is the only way to change the variable in javascript inside the function, i.e. I should always do

source = function(source);to change the variable inside the function,

or am I missing the concept of an area that is stopping me from doing this?

+3
source share
2 answers

A function modifyTestessentially creates a local function level variable called s; this variable exists only within the framework of the function; therefore, its change will not affect the external volume.

, :

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

, , - :

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

, :

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
+7

" ". JavaScript ( ) , , , , .

. , , .

+3

All Articles