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
(对于该调用)。因为箭头函数在创建时是绑定的,所以它们的这个值不能更改。完美的解释!你能加上这个吗?