Reputation: 1948
Found this piece of code somewhere:
function Name1(name){
this.name = name;
}
var name = new Name1("11");
document.write(name.name);
Output:
IE11 - "11"
Firefox43 - "undefined"
Just interested to know why is it and what should be the correct output?
Upvotes: 1
Views: 35
Reputation: 1074218
You're apparently running this at global scope. Global variables declared with var
become properties of the global object.1 On browsers, that object is window
. window
already has a property called name
: It's the name of the window (if any). On Firefox, it can only be a string, so assigning an object to it is ignored; IE is apparently more lenient (and arguably, as of the HTML5 spec, wrong; name
is defined as a DOMstring
). So name = new Name1("11")
ends up being a no-op on Firefox, and name.name
(reading the name
property of a string) yields undefined
.
If you change the name of the variable, you get the same output on both browsers:
function Name1(name){
this.name = name;
}
var x = new Name1("11");
console.log(x.name);
Conflicts like this are one of the many, many reasons to avoid running code at global scope if you can help it; wrap things in scoping functions:
(function() {
function Name1(name){
this.name = name;
}
var name = new Name1("11");
console.log(name.name);
})();
1 In contrast, global variables declared with let
do not become properties of the global object, which immediately raises the question of: What is the output of the following script with let
on Firefox?
// REQUIRES ES2015+ SUPPORT
function Name1(name){
this.name = name;
}
let name = new Name1("11");
console.log(name.name + " (" + typeof name + ")");
And the answer, satisfyingly, is that it outputs "11 (object)" (so does Chrome, which also correctly outputs undefined
for your original example), whereas the above with var
(https://jsfiddle.net/s1j11023/) outputs "undefined (string)":
// REQUIRES ES2015+ SUPPORT
function Name1(name){
this.name = name;
}
var name = new Name1("11");
console.log(name.name + " (" + typeof name + ")");
Upvotes: 4