Search code examples
javascriptjquerybackbone.js

return $.extend and this in backbone


I'm working on a component architectural project and I saw this piece of code.

clone : function() {
    return $.extend(true, {}, this);
}

What does this even means? Pass this into an object using $.extend?


Solution

  • It seems like clone is a method of an object that simply creates a clone of the original object. You could say it's a way to create a real copy of an object, not just a reference to it. So this refers to the object the method belongs to.

    var obj = {
      one: 1,
      two: 2,
      three: 3,
      clone: function() {
        return $.extend(true, {}, this);
      }
    };
    
    var clone = obj.clone();
    
    obj.one = "one";
    
    console.log(obj);
    console.log(clone);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>