简体   繁体   中英

JS - passing by reference an object

Given the code below I create an object called foo and I want to make 'a' equal to true from my function called maketrue(obj).

var foo = {a: false, b: false, c: false}

 function maketrue(obj)
 {
 obj = true;    
 }

 maketrue(foo.a); // I want to make 'a' true from the function

 console.log(foo.a);

Why does it return false still?

I have looked at similar questions that worked passing an object but my method doesn't pass by reference.

You're not passing the object as an argument (that would be passed by reference), you're passing in only the boolean value of the object's property (pass by value).

If you want something like this would work:

 var foo = {a: false, b: false, c: false}

 function maketrue(obj, val)
 {
 obj[val] = true;    
 }

 maketrue(foo, 'a'); // I want to make 'a' true from the function

 console.log(foo.a);

In JavaScript objects are represented as references. foo.a is not an object, foo however, is. Try this:

 var foo = {a: false, b: false, c: false}

 function maketrue(obj)
 {
 obj.a = true;    
 }

 maketrue(foo);

 console.log(foo.a);

Change it to:

var foo = {a: false, b: false, c: false}

 function maketrue(obj)
 {
 obj.a = true;    
 }

 maketrue(foo);

 console.log(foo.a);

Working with and in Javascript:

var foo = {a: false, b:false, c:false}    

/**
 * Way Object
 */
function maketrue(obj)
{   
    obj.a = true;  // Specific property
}
maketrue(foo);

/**
 * Way Property
 */
function maketrue(obj, prop)
{   
    obj[prop] = true;  // property as a parameter
}
maketrue(foo, 'a');

console.log(foo.a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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