简体   繁体   中英

Overriding an object that was passed to a function

I was wondering recently if this is possible: Passing an object to a function and overriding the entire object with a complete different object inside of that function, so that its value is permanently modified. Since objects are passed by reference, I have a feeling that it must work somehow but I have no idea how. To put it in code, it should do something like this:

function a() {
    console.log("i am a");
}

function b() {
    console.log("i am b");
}

function override(func1, func2) {
    func1 = func2;
}

override(a, b);

a(); //"i am b" expected

FIDDLE

This obviously doesn't work because I'm just overriding the variable func1 but I think you get the idea. And I chose to use functions instead of pure objects, because you could easily "override" an object by just deleting its properties and copying the new properties from the second object. But that's not what I want.

And before you ask, I'm not trying to solve any real life problem with this, I'm just asking out of curiosity. So is there a way to achieve this and if not, is there a reason why not?

Thanks!

This doesn't work because although JS passes references to functions that just means that your func1 and func2 parameters end up referring to the same functions (objects) that the identifiers a and b refer to but when you change what func1 refers to that doesn't affect what a refers to.

To put it another way, when you pass an object to a function the function can change the content of the object by modifying, adding or deleting properties, but it can't change which object a variable outside the function refers to. (At least, not via the function's own argument - a function can modify variables in its scope chain up to and including global variables, but it has to do so by referring to them by their own names.)

In your code

function override(func1, func2) {
    func1 = func2;
}

func1 is a variable that points to function a and func2 is a variable that points to function b . The statement func1 = func2 makes func1 point to b. It does not change anything outside the function override .

Please use objects to make use of pass by reference . The code given below illustrates how it works.

function a() {
    console.log("i am a");
}

function b() {
    console.log("i am b");
}

var object1 = {
   func1:a
};

var object2 = {
   func2:b
}


function override(object1, object2) {
    object1.func1 = object2.func2;
}

override(object1, object2);

object1.func1(); //"i am b"

This code is just for demonstration, might not be useful in a real scenario.

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