繁体   English   中英

等效于JavaScript中的Object.assign()

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

Object.assign一个常见用例是在不更改对该对象的引用的情况下修改(或完全替换)对象的属性,因此具有该引用的其他内容也将被更新。

有没有办法用函数的内容来做到这一点?

因此,例如:

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

有没有办法修改/替换函数的内容?

不,那是完全不可能的。 函数的行为(即调用函数的行为)在Javascript中是不可变的。

当然,如果您事先知道要更改该函数的行为,则可以使该函数成为一个依赖于某些外部可交换状态的闭包,以确定该做什么:

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'

首先,在您的示例中我不了解一件事,即const的使用。 如果在第3行重新分配b ,为什么还要使用const b

无论如何,在Javascript中,大多数变量都使用引用。 所以,举例来说,在下面的代码中, 常量被定义为函数和变量b一个参考,分配一个新的功能到B所以当你真正分配为好。

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

希望我不要错过你的意思。

编辑#1

与其将函数a声明为const,然后将其重新分配,我不打算将该函数存储在静态对象中。 这样,对象引用/指针本身就是一个常量,但是它的内容,它的属性并不被认为是不可变的。 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(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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