Search code examples
javascriptthisprototype

Save context this


I found some interesting problem. Task is to make wrapper to all child-functions, that will delay implementation.

function someFunc() {
  console.log(this.someProp);
}

var obj1 = {
  someProp: 1,
  method1: someFunc,
};

var obj2 = {
  someProp: 2,
  method2: someFunc,
};
Function.prototype.defer = function(ms) {
  let self = this;
  setTimeout(self, ms) //<<-- lose context(obj1, obj2)
};
obj1.method1(); // 1
obj2.method2(); // 2
obj1.method1.defer(1000); // 1 after 1 sec, now is undefined
obj2.method2.defer(1000); // 2 after 1 sec, now is undefined

Solution

  • Try preserving the execution context using the bind. bind() allows set which specific object will be bound to this when a function or method is invoked.

    function someFunc() {
      console.log(this.someProp);
    }
    
    var obj1 = {
      someProp: 1,
      method1: someFunc,
    };
    
    var obj2 = {
      someProp: 2,
      method2: someFunc,
    };
    Function.prototype.defer = function(ms) {
      setTimeout(this, ms) //<<-- lose context(obj1, obj2)
    };
    obj1.method1(); // 1
    obj2.method2(); // 2
    obj1.method1.bind(obj1).defer(1000); // 1 after 1 sec, now is undefined
    obj2.method2.bind(obj2).defer(1000); // 2 after 1 sec, now is undefined