0
function guns() {
    console.log(this.had);
}

var had ="guts";

var stun = {
    had : "cuts",
    guns: guns

};

var murn = {
    had : "mork"
};

guns();

stun.guns();

guns.call( murn );

new (guns);

I used this code in visual code studio and my browsers console, but when I run the code in these two places the result is different. In in my browsers console I get guts, cuts, mork, and undefined. In visual studios code I get undefined, cuts, mork, and undefined. Why does this happen? I'm new to javascript and programming and this is very confusing to me. I greatly appreciate any help.

charlietfl
  • 164,229
  • 13
  • 110
  • 143
  • 3
    Simple answer is to do `console.log(this)` ... will see it is different in the two environments. Read up on how `this` works. Not hard to find lots of information on it – charlietfl Jul 13 '17 at 00:46
  • Different UIs / Layers. If your are posting to web, test your JS in browser console. – fred randall Jul 13 '17 at 00:49
  • In general, you shouldn't use `this` in a function that isn't being called on an object. – Barmar Jul 13 '17 at 00:51
  • Use `had = "guts"` instead of `var had = "guts"` to make it a global variable in all environments, or use [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) so that `this` itself is `undefined` in the `guns()` call as proper. – Bergi Jul 13 '17 at 01:43

0 Answers0