getting can't read property 'any' type error when we script in strict mode

63 Views Asked by At

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:

enter image description here

foo(); is causing the problem. if I remove "use strict" everything is working fine.

Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

In strict mode, when you call a function without doing anything to set its this, this is undefined, not a reference to the global object. It's one of the big differences in strict mode. So if you want to call foo with a reference to the global object, you either:

  1. At global scope, do foo.call(this); (since this at global scope is a reference to the global object), or

  2. On browsers, do foo.call(window); (since window 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:

"use strict";
var bar = "global";

function foo() {
    console.log(this.bar);
}



var obj1 = {
    bar: "obj1",
    foo: foo
};

var obj2 = {
    bar: "obj2"
};

foo.call(this); // <=== changed

obj1.foo();
foo.call(obj2);
new foo();

...and of #2:

"use strict";
var bar = "global";

function foo() {
    console.log(this.bar);
}



var obj1 = {
    bar: "obj1",
    foo: foo
};

var obj2 = {
    bar: "obj2"
};

foo.call(window); // <=== changed

obj1.foo();
foo.call(obj2);
new foo();

1
On
function foo() {
    console.log(this.bar);
}

'this' refers to the scope of the function foo. you can either type bar in which the scope is implied to be window which is the global scope. or you can type window.bar.

function foo() {
   console.log(window.bar);
   console.log(bar);
}