Javascript 如何使Object.assign工作? 背景

Javascript 如何使Object.assign工作? 背景,javascript,node.js,ecmascript-6,assign,Javascript,Node.js,Ecmascript 6,Assign,我试图通过object.assign扩展旧对象的功能,方法是传入一个具有附加功能的新对象 constoldobj=()=>{ const printLog=()=>console.log(“hello”); 返回{printLog}; }; 常量newObj=()=>{ 常数测试=()=>{ printLog();//此处失败! console.log(“世界”); }; 返回{test}; }; const mix=Object.assign(oldObj(),newObj()); mix.

我试图通过
object.assign
扩展旧对象的功能,方法是传入一个具有附加功能的新对象

constoldobj=()=>{
const printLog=()=>console.log(“hello”);
返回{printLog};
};
常量newObj=()=>{
常数测试=()=>{
printLog();//此处失败!
console.log(“世界”);
};
返回{test};
};
const mix=Object.assign(oldObj(),newObj());
mix.printLog();

mix.test()编辑:将代码更改为:

   const oldObj = () => { 
        const printLog = () => console.log("hello");
        return {printLog};
    };

    const newObj = () => {   
        function test() {
            this.printLog(); 
            console.log("world");
        };
        return {test}; 
    };

    const mix = Object.assign(oldObj(), newObj());


    mix.printLog();
    mix.test();

编辑:将代码更改为:

   const oldObj = () => { 
        const printLog = () => console.log("hello");
        return {printLog};
    };

    const newObj = () => {   
        function test() {
            this.printLog(); 
            console.log("world");
        };
        return {test}; 
    };

    const mix = Object.assign(oldObj(), newObj());


    mix.printLog();
    mix.test();

要访问
printLog
,您必须通过
this
访问它。但是,您的函数
test
不能是箭头函数,因为箭头函数使用它们在其中定义的上下文的
this
上下文,所以要获得所需的结果,请将
printLog()
更改为
this.printLog()
并将
test
从箭头函数切换为常规函数:

constoldobj=()=>{
const printLog=()=>console.log(“hello”);
返回{printLog};
};
常量newObj=()=>{
常量测试=函数(){
this.printLog();//此处失败!
console.log(“世界”);
};
返回{test};
};
const mix=Object.assign(oldObj(),newObj());
mix.printLog();

mix.test()要访问
打印日志
,您必须通过
访问它。但是,您的函数
test
不能是箭头函数,因为箭头函数使用它们在其中定义的上下文的
this
上下文,所以要获得所需的结果,请将
printLog()
更改为
this.printLog()
并将
test
从箭头函数切换为常规函数:

constoldobj=()=>{
const printLog=()=>console.log(“hello”);
返回{printLog};
};
常量newObj=()=>{
常量测试=函数(){
this.printLog();//此处失败!
console.log(“世界”);
};
返回{test};
};
const mix=Object.assign(oldObj(),newObj());
mix.printLog();

mix.test()哦,我明白了。让我再看一看。请允许我更正。我想要的输出是
hello\nworld
。请查看@SimpleJ的解释。您更改了什么,为什么?我更改了打印日志以访问此.printLog。printLog函数是this引用的对象的一个属性。哦,我明白了。让我再看一看。请允许我更正。我想要的输出是
hello\nworld
。请查看@SimpleJ的解释。您更改了什么,为什么?我更改了打印日志以访问此.printLog。printLog函数是“this”引用的对象的属性。很好的解释。因此,箭头函数将使用
newObj
this
上下文,该上下文没有
printLog
函数。但是
函数如何访问它呢?你能解释一下吗?正确。默认情况下,常规的
函数
没有此
绑定。当您使用点语法(
object.method()
)调用方法时,该方法将绑定到该对象,因此当您调用
mix.test()
时,
test
将绑定到
mix
(对于该调用)。因为箭头函数在创建时是绑定的,所以它们的
这个
值不能更改。完美的解释!你能加上这个吗?很好的解释。因此,箭头函数将使用
newObj
this
上下文,该上下文没有
printLog
函数。但是
函数如何访问它呢?你能解释一下吗?正确。默认情况下,常规的
函数
没有此
绑定。当您使用点语法(
object.method()
)调用方法时,该方法将绑定到该对象,因此当您调用
mix.test()
时,
test
将绑定到
mix
(对于该调用)。因为箭头函数在创建时是绑定的,所以它们的
这个
值不能更改。完美的解释!你能加上这个吗?