简体   繁体   中英

Equivalent of Object.assign() for a function in JavaScript

A common use-case for Object.assign is to modify (or flat out replace) the properties of an object without changing the reference to the object, so other things that have that reference are also updated.

Is there a way to do this with the contents of a function as well?

So, for example:

const a = () => console.log('a');
const b = a;
doSomethingMagicalHere(b, () => console.log('b'));
b(); // prints 'b'
a(); // prints 'b'

Is there a way to modify/replace the contents of a function?

No, that's outright impossible. The behaviour of a function (ie what calling it will do) is immutable in Javascript.

Of course, if you know beforehand that you will want to alter the behaviour of the function, you can make the function a closure that relies on some external, exchangeable state to determine what it should do:

const a = function f(...args) { return f.contents.call(this, ...args); }
a.contents = () => console.log('a');
a(); // prints 'a'
Object.assign(a, {contents(){ console.log('b') }});
a(); // prints 'b'

First, there is one thing I don't understand in your sample, the use of const . Why use const b if you reassign b on line 3 ?

Anyhow, in Javascript, most variables use references. So, for instance, in the following code, the const a is defined as a function and the variable b is a reference to a , so when assigning a new function to b , you actually assign a as well.

const a = () => console.log('a');
var b = a;
b = () => console.log('b');
a(); // prints 'b'

I hope I didn't miss your point.

Edit #1

Rather than declaring a function a as a const which will be reassigned afterward, I'd store that function in a static object. The object reference/pointer itself is then a constant but its content, its properties, aren't considered as immuatables. ( https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75#.whv1jizih )

 // Define a constant reference/pointer to the static object oA const oA = { // Define mutable property "f" f: () => console.log('a') }; // Define an other const ref to the same object called oB const oB = oA; // Update the value pointed by the oB.f ref oB.f = () => console.log('b'); // Call oB.f // 'b' expected oB.f(); // Call oA.f // 'b' expected oA.f(); // Using Object.defineProperty Object.defineProperty(oA, 'f', { __proto__: null , value: () => console.log('f') }); // Call oB.f // 'f' expected oB.f(); // Call oA.f // 'f' expected oA.f(); 

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