On the problem of this pointing in JavaScript, how does it behave differently in chrome controller and node environment?

function foo() {
    var a = 2;
    this.bar();
}

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

foo(); //undefined

when this code is executed in the chrome console, it will not report an error and can be executed.
but in a node environment, the error "TypeError: this.bar is not a function" is reported directly.
excuse me, how to effectively understand this situation?

Aug.25,2021

is really not a strict mode question. The previous answer is incorrect.
after testing, the main code running in a non-strict module will produce the error prompt mentioned by the subject.
at this point, this points to unexported function defined by module.exports, in the function. All unexported function will not be mounted on module.exports.


node's this points not to window but to global


. < H2 > in browser: < / H2 >
function foo() {
    var a = 2;
    this.bar();
}

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

actually:

window.foo = function() {
    var a = 2;
    window.bar();
}

window.bar = function() {
    console.log( window.a );
}
< H2 > in NODE: < / H2 >
function foo() {
    var a = 2;
    this.bar();
}

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

actually:

function foo() {
    var a = 2;
    global.bar();
}

function bar() {
    console.log( global.a );
}

is explained as follows:
the this in the global refers to module.exports
in the function this points to the global object
for more information, please see link

.

tell me a wool. If node defaults to strict mode, why do you need use strict'? this points to strict mode and normal mode. There is a difference between strict mode and normal mode

. < hr >

node run a comparison of two pieces of code that may help you:

'use strict'
function fn() {
    console.log(this === global)
    console.log(this)   // this  undefined
}
let obj = {name: 'obj'}

fn()
fn.call(obj)
// 'use strict'
function fn() {
    console.log(this === global)     // true  false 
}
let obj = {name: 'obj'}

fn()
fn.call(obj)

strict mode error reporting can be this error?
TypeError: this.bar is not a function
node is strict by default? Give me a chance to learn and attach the document to me
.

this in node
Global this points to module.exports
function body this points to global two objects that are not the same can be tested in person

.

this, of node point to global try

Menu