Search code examples
javascriptjavascript-objects

Object.assign rebind of functions


since I need reputation and can't actually comment on this thread: Object.assign methods not binding 'this' Im opening my own question:

Can this be somehow solved or workarounded? I have a "master" object containing

function init(){ console.log(this) }.bind(this)

I am cloning this master object into other object and i want the init function run with the scope of the slave object, not the master. Is there any option?


Solution

  • Actually solved my problem thanks to this:

    https://gist.github.com/cowboy/5373000

    In case the URL is down, here is the additional code:

    Function.prototype.bind = (function(origBind) {
      return function() {
        var fn = origBind.apply(this, arguments);
        fn.__origFn__ = this.__origFn__ || this;
        return fn;
      };
    }(Function.prototype.bind));
    
    Function.prototype.unbind = function() {
      return this.__origFn__;
    };