Sunday, November 4, 2018

javascript - How to update original this when cloning with extend

I'm trying to clone some objects using the jquery extend method. However, after cloning my object, I realized that some methods of the cloned object were modifying values from the original object so I thought both objects properties may be pointing at the same variable.


After running some tests, I figured that the properties of my cloned object got copied correctly... including the local self variable (which is used to hold the reference to the original this of the class instance). Since the cloned self is still pointing at the original instance, the methods referring to that variable are targeting the properties of the original instance instead of it's own instance:


var Animal = function() {
var self = this;
this.sound = "";
this.talk = function(){
alert(self.sound);
};
};
var dog = new Animal();
dog.sound = "Woof";
dog.talk(); //Woof as expected
var cat = $.extend(true, {}, dog);
cat.sound = "Meow";
cat.talk(); //Woof... but Meow was expected

The extend method behavior does make sense... but is there a generic way to make sure the self variable refers to the new cloned object? By generic, I mean that the self variable may have a different name (that, _this, etc) and that I would like to avoid adding custom methods to every class just to update the self variable.


You should also keep in mind that the self variable is private (and there's many good reasons to keep it like this) so this mean you can't set it outside the instance.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...