1

When I change the isPublish property of localCampaign after copying the campaignData in that, the isPublish property of campaignData also get changed, "can see the comments in code below where this is happening"

export class CampaignNotificationDetailPage {
campaignData: any;

   publishCampaign() {
  let localCampaign = this.campaignData;
  localCampaign.isPublish = true;  //this also updates the this.campaignData.isPublish to true?
    }
   }

How to block the changes in campaignData and why this is happening?

  • make a copy of the this.campaignData and assign to let localCampaign. Here call by reference is happening. By default javascript objects and arrays work as call by reference. – Franklin Pious May 10 '18 at 11:24

4 Answers4

2

This is because localCampaign is assigned with this.campaignData. Now this.campaignData is pointing to on location say reference location

And when you say

localCampaign=this.campaignData;

You are nothing but pointing localCampaign to the reference location of this.campaignData

Hence when this.campaignData changes, localCampaign changed gradually as they are pointing to same reference location. This concept is called call by reference.

You can assign a cloned object to localCampaign

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

Now you can use above method to clone this.campaignData

let localCampaign=clone(this.campaignData);
Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
1
let localCampaign = JSON.parse(JSON.stringify(this.campaignData));

This will make a copy.

Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
1

Yes, It changes the campaignData value, even though the let is block scoped.

When we do

let localCampaign = this.campaignData;

localCampaign is pointing to this.campaignData, and when you change values in localCampaign, it gets reflected in this.campaignData.

And after the publishCampaign's black (i.e. {}), the localCampaign will be removed from the memory.

Basavaraj Bhusani
  • 5,375
  • 2
  • 16
  • 24
1

object in javascript are reference type , so you must find a way to apply clone the object , this is one way to solve this :

export class CampaignNotificationDetailPage {
 campaignData: any;

    publishCampaign() {
    let localCampaign = object.assign({},this.campaignData);
    localCampaign.isPublish = true; 
    }
   }

another way :

export class CampaignNotificationDetailPage {
  campaignData: any;

       publishCampaign() {
       let localCampaign  {...this.campaignData}
       localCampaign.isPublish = true; 
        }
       }

this answer give a good explanation How to Deep clone in javascript

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91