KrIsHnA KrIsHnA - 22 days ago 7
Javascript Question

name already defined in console!?

Could anyone explain why this code returns


""


in firebug console?

Don't down-vote thinking it's just a typo! :O
I was curious to know why it doesn't throw an error!!!

function mds() {
var {
namex,
score,
className
}
= {
namex: 'NAME',
score: '10',
className: 'Oop'
};
this.test = function () {
return name;
};
}
var x = new mds();
x.test()


I would also love to hear more details on this type of variable mapping (or a link) ?




UPDATE:

I would like to know why name is predefined with value "" in console?

Answer

The JavaScript part of the explanation here is simple.

When you do this:

  this.test = function () {
    return name;
  };

It will first look for a variable named name in the scope of the function this.test(). When name is not found there, it will check in the parent function's scope as well. And since name is not defined there as well, it will look in the global scope, which is window, and returns the value of window.name, which in this case is an empty string. This (window.name) is what you are seeing when you run name in the console (or Firebug). This much is simple.

The value of window.name is decided according to it's definition in the HTML Standard (not according to ECMAScript rules). This MDN page says:

window.name - Gets/sets the name of the window.

And in your case, the name of the window is empty, hence the empty string you are getting. That's the simpler explanation of why window.name is empty.

If you really want to understand why window.name is empty here, you need to check out the HTML Specification for what it says about browsing contexts. It says that the value of window.name will be the name of the current browsing context.

A browsing context is an environment in which Document objects are presented to the user. (from the spec)

For example, when you create a link in HTML using the below code, the target attribute specifies the target browsing context in which the page is to be opened.

<a href="page.html" target="TargetName">Click me</a>

See more examples in this JSBin.

Hope this was somewhat helpful. Read the HTML Spec to understand more about browsing contexts.