Search code examples
javascriptbind

js log binded object


I have a function binded to an object, how can I access to the object at the same scope with the function?

let f = function(){};
class A{}
f = f.bind(new A());
// console.log(f.bindedObject)

what about in a method?

class B{
    constructor(func){
        this.func = func;
    }

    log(){
        // console.log(this.func.bindedObject)
    }
}

class A{}
let b = new B(function(){}.bind(new A()));
b.log()

Solution

  • You could overwrite the bind method

    (function() {
        let bind = Function.prototype.bind;
        Function.prototype.bind = function(newThis) {
            let bf = bind.apply(this, arguments);
            bf.newThis = newThis;
            return bf;
        };
    })();
    
    var f = function() {};
    var nf = f.bind({'hello':1});
    console.log('newThis', nf.newThis);