javascriptclass-constructors

Why after defining some method from object to variable context lost?


please help to get answer i can't understand why the context lost after defination

    class A {
    	func() {
    		console.log(this)
    	}
    }
    
    let a = new A();
    let b = a.func;
    b();


Solution

  • You can refer to this in order to clarify your doubt.

    Simple this short if you call a function on object javascript considers that object as its this/context.

    eg.

    let obj = {
       key : 'value',
       fun : function(){
    
       }
    }
    // if called like obj.fun() --> obj is going to be this
    // if called like let ffun = obj.fun; ffun();  ---> window/global object is going to be this
    

    If you call that method by using call/apply/bind you need to specify custom context as first parameter to these methods.

    //if call like obj.fun.call(someObject, p1, p2)
    // Or obj.fun.apply(someObject, [p1, p2])
    // Or let ffun = obj.fun.bind(someObject, [p1, p2]);   ffun();
    // someObject is going to be this in all these 3 cases
    

    In otherwise cases where a function is directly called it takes window/global object as its context.