简体   繁体   中英

Understanding console.log(console.log(object))

I am new to programming and js and I am trying to learn crux of javascript.

var obj1 = {
    name: 'rawn',
    fn: function() {
        console.log(this);
    }
};
console.log(obj1.fn());

When I output this I get the object(as expected) - {name: "rawn", fn: ƒ} and on another line I get - undefined . So my question is why and how do I get undefined ?

My understanding is that, we are writing this line - console.log(obj1.fn()); as , console.log(console.log(this)) , so how does javascript engine gives the result as undefined (what was put as undefined in the execution context)?

console.log(obj1.fn()) and console.log(console.log(this)) are not equivalent at all, but they actually have the same result for the same reason: the inner function does not return anything . The return value of these functions is undefined . Which is what the outer console.log logs.

This is because of two reasons. First, in console.log(this); the context of this inside the fn function is the object itself. Hence it prints the guts of obj1 .

Secondly, in console.log(obj1.fn()); , you are actually calling the method which returns nothing. Instead if you say console.log(obj1.fn); it will return:

ƒ () { console.log(this); }

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM