-2

I'm new to JavaScript, I can't find a clear answer to what's going on here:

function bike() {
  console.log(this.name);
}

var name = "John";
var obj1 = {
  name: "Sam",
  bike: bike
};
var obj2 = {
  name: "Paul",
  bike: bike
};

bike(); // undefined
obj1.bike(); // Sam
obj2.bike(); // Paul

I don't understand why it's printing 'undefined' on the terminal instead of 'John'

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
beginCS
  • 13
  • 3
  • 7
    but here it shows `John` – Devsi Odedra Dec 10 '19 at 05:32
  • 1
    Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – ASDFGerte Dec 10 '19 at 05:34
  • its printing John – prisar Dec 10 '19 at 05:34
  • @DevsiOdedra any idea why it would show undefined when I run it on my terminal? – beginCS Dec 10 '19 at 05:35
  • @ASDFGerte I see thank you! – beginCS Dec 10 '19 at 05:40
  • Please also note, that in a browser context, you collide with `window.name`. You can write to the property, but it is a setter, that autoconverts to string. Just as a side note. – ASDFGerte Dec 10 '19 at 05:49
  • it prints john, because the snippet is not in strict mode (undefined/null this gets converted to window), and global variables get added to window. It **should** throw, "cannot read property `name` of `undefined`". I don't know what your terminal is doing. – ASDFGerte Dec 10 '19 at 05:55

2 Answers2

1

Nothing wrong with this Behaviour,

function bike() {
  console.log(this.name);
}

var name = "John";
var obj1 = {
  name: "Sam",
  bike: bike
};
var obj2 = {
  name: "Paul",
  bike: bike
};

bike(); // undefined here it refers to (**this**).name
        //if you run the same in browser console 
        // you will get jhon
        // but in node there is no window object
        // that's y you are getting undefined in node terminal

obj1.bike(); // Sam
obj2.bike(); // Paul

Plz refer the link ASDFGerte suggested for more

Purushoth.Kesav
  • 615
  • 7
  • 16
-2

it's Simple you just write

window.name

window.variableName it is used to print global variable

dhruvin prajapati
  • 184
  • 1
  • 3
  • 15