0

I'm completely new to JS and trying to learn on my own. Using below code -

var me = {
    name: {first:"justin"}
},
name = me.name;

name = {first: "alexis"};

Why would document.write(me.name.first + "</br>"); return justin?

and

why would document.write(this.name.first); doesn't return anything?

Please can you explain me?

Thanks, Me

VD27
  • 31
  • 7
  • because the doc.write code is not defined inside the object you created, so `this` has a differant context (its context is whatever object the code exists as part of, in this case, the page, I think). using `me` fully qualifies the instance of the object, so it works correctly. – Frank Thomas Dec 02 '15 at 20:07
  • In what context are you executing those `document.write()`s? Right after the snippet you posted? – acdcjunior Dec 04 '15 at 02:24
  • What do you expect `me.name.first` to be? You never assign any other value to `me.name` or `me.name.first` (that is, you have no `me.name = ...` or `me.name.first = ...` statements in your code). – apsillers Dec 04 '15 at 02:28
  • 1
    As for why `this.name.first` doesn't work as you expect, see [Using the variable “name” doesn't work with a JS object](http://stackoverflow.com/q/10523701/710446). `this.name` is probably being set to the string `[object Object]`, which does not have a `first` property. – apsillers Dec 04 '15 at 02:29
  • acdcjunior - Yes, that's correct. This code is part of video tutorial and I'm trying to understand the behavior. – VD27 Dec 04 '15 at 10:07
  • @apsillers - This makes sense now. Thank you for your help. So, avoid using "name" as the variable or object name in global execution context, right? – VD27 Dec 04 '15 at 10:16

1 Answers1

1

Just change the variable name name to other string, for example: n. Everything will work perfect.

var me = {
   name: {first:"justin"}
},
n = me.name;

n = {first: "alexis"};

The reason is this.name.first will refer to window.name.first. But window.name has special usage in javascript and has to be a string.

JasmineOT
  • 1,978
  • 2
  • 20
  • 30
  • That explains. So, avoid using "name" as the property or variable name. Basically, treat them as reserve words, is it good practice? Can I use them inside the objects ("me" in my example). Thank you again. – VD27 Dec 04 '15 at 10:14
  • @DV27 You can use it as property name. Also you can use it as a local scope variable name. Just avoid using it as a global variable name. – JasmineOT Dec 04 '15 at 10:36