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'
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
it's Simple you just write
window.name
window.variableName it is used to print global variable
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.