简体   繁体   English

在传播 object 时使用“this”关键字

[英]Use 'this' keyword while spreading an object

I have an unusuall problem.我有一个不寻常的问题。 What I try to achive is to modify an object's property while spreading via method.我试图实现的是在通过方法传播时修改对象的属性。 Example例子

const obj1 = {
    prop1: "value1",
    prop2: function() {
        this.prop1 = 10
        return "value2"
    }
}
const obj2 = {
    ...obj1,
    prop2: obj1.prop2()
}

And now, I would like obj2 to look like this:现在,我希望 obj2 看起来像这样:

{
    prop1: 10,
    prop2: "value2"
}

But beacause of this's scoping only prop1 in obj1 gets changed and obj2 looks like this:但是由于这个范围限定,只有 obj1 中的 prop1 被更改,而 obj2 看起来像这样:

{
    prop1: "value1",
    prop2: "value2"
}

I know that I could change obj1.prop1 directly afterwards, but the thing is that second part of the code (obj2 initialization) is in one of the packages my project use, and do not want to modify it.我知道之后我可以直接更改 obj1.prop1,但问题是代码的第二部分(obj2 初始化)在我的项目使用的包之一中,不想修改它。 The only thing I control is the obj1 that I pass further.我唯一控制的是我进一步传递的 obj1。 Is there any way to do that without modifing source code of a package?有没有办法在不修改 package 的源代码的情况下做到这一点?

You can achieve it by changing the obj2 initialization to this:您可以通过将obj2初始化更改为此来实现它:

const obj2 = {
    prop2: obj1.prop2(),
    ...obj1,
    prop2: obj1.prop2(),
}

But like others mentioned in the comments - this is very smelly...但就像评论中提到的其他人一样 - 这很臭......

In this snippet:在这个片段中:

const obj1 = {
    prop1: "value1",
    prop2: function() {
        this.prop1 = 10
        return "value2"
    }
}

modifying prop1 in the prop2 getter function is a side effect, and is considered to be code smell .prop2 getter function 中修改prop1是一个副作用,被认为是code smell

I dont know you're use case, but maybe you could do the following.我不知道您是用例,但也许您可以执行以下操作。 obj3 would contain your needed result obj3将包含您需要的结果

 const obj1 = { prop1: "value1", prop2: function () { this.prop1 = 10; return "value2"; } }; const obj2 = {...obj1, prop2: obj1.prop2() }; const prop2 = obj1.prop2; const prop2Value = obj1.prop2(); const obj3 = {...obj1, ...prop2, prop2: prop2Value}; console.log(obj1); console.log(obj2); console.log(obj3);

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

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