0

I am trying to use the "this" keyword inside a function, this works

var test = function(){
    console.log(this); //console logs the window object
}
(function(){
    test();
});

However when I try and use strict mode this is undefined?

'use strict';
var test = function(){
    console.log(this); //undefined
}
(function(){
    test();
});

I wish to know if its possible to access the this keyword from inside function in strict mode?

Any help highly appreciated.

So for anyone facing same issue This works

'use strict';
var test = {
    fname:'kalesh',
    check: function(){
        console.log(this.fname);
    }
};
(function(){
    test.check();
})();

It appears that in strict mode have to be inside an object to use this keyword and not only inside function

1 Answers1

1

If you just want to apply the window object to this, you can use call(window) or apply(window)

Apply: https://www.w3schools.com/js/js_function_apply.asp

Call: https://www.w3schools.com/js/js_function_call.asp

mpm
  • 314
  • 1
  • 14