while using strict mode
I'm getting type error
to access the var
using this
.
"use strict";
var bar = "global";
function foo() {
console.log(this.bar);
}
var obj1 = {
bar: "obj1",
foo: foo
};
var obj2 = {
bar: "obj2"
};
foo();
obj1.foo();
foo.call(obj2);
new foo();
Screen shot:
foo();
is causing the problem. if I remove "use strict"
everything is working fine.
Thanks in advance.
In strict mode, when you call a function without doing anything to set its
this
,this
isundefined
, not a reference to the global object. It's one of the big differences in strict mode. So if you want to callfoo
with a reference to the global object, you either:At global scope, do
foo.call(this);
(sincethis
at global scope is a reference to the global object), orOn browsers, do
foo.call(window);
(sincewindow
is a property on the global object it uses to point to itself -- other environments may also have other similar globals)Here's an example of #1:
...and of #2: