How can i get variable in handler function of obj? Without reference of the obj in MyClass.
    var obj = {
        func: function(){
            var myClass = new MyClass();
            myClass.handler = this.handler;
            myClass.play();        
        },
        handler: function(){
            //Here i don't have access to obj
            console.log(this); //MyClass
            console.log(this.variable); //undefined
        },
        variable:true
    };
    function MyClass(){
        this.play = function(){
            this.handler();
        };
        this.handler = function(){};
    };
    obj.func();
 That's construction need you, if you use Base.js or another similar way of oop.
_.bindAll(obj) (underscore metod) also not suitable. It's break overriding in Base.js.
Bind only handler method: http://jsfiddle.net/uZN3e/1/
var obj = {
    variable:true,
    func: function(){
        var myClass = new MyClass();
        // notice Function.bind call here
        // you can use _.bind instead to make it compatible with legacy browsers
        myClass.handler = this.handler.bind(this);
        myClass.play();        
    },
    handler: function(){
        console.log(this.variable);
    }
};
function MyClass(){
    this.play = function(){
        this.handler();
    };
    this.handler = function(){};
};
obj.func();
                        Use a variable to refer original context:
...
var self = this;
myClass.handler = function(){ self.handler(); };
...
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With