How to update the original when cloning with the extension

I am trying to clone some objects using the jquery extension method. However, after cloning my object, I realized that some methods of the cloned object change the values ​​from the original object, so I thought that both properties of the objects could point to the same variable.

After running some tests, I realized that the properties of my cloned object were copied correctly ... including a local variable self(which is used to store a reference to the original thisinstance of the class). Since the cloned selfis still pointing to the source instance, the methods related to this variable focus on the properties of the source instance instead of its 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

... , self ? , self ( _this ..) self.

, self ( , ), , .

+4
2

var self = this.

: http://jsfiddle.net/quwdeafd/
this. , ?

var Animal = function() {

  this.sound = "";
  this.talk = function(){
      console.log(this); //Logs Animal the first time, object the second 
      console.log(this.sound); //Logs Woof and meow 
  };

};

var dog = new Animal();
dog.sound = "Woof";
dog.talk(); 

var cat = $.extend(true, {}, dog); 
cat.sound = "Meow";
cat.talk(); 

: :

Animal.prototype.talk = function(){
      console.log(this); 
      console.log(this.sound);
  };

.

+3

, . extend , . , , .

extend , , , SO-.

+1

Source: https://habr.com/ru/post/1570387/


All Articles