Reputation: 8482
Can you please explain the following piece of code, ? it is working in my browser console. So how does this work ? The new keyword doesnt create a new instance at all or how is it ?
var myObject = new Object(); // Produces an Object() object.
myObject['0'] = 'f';
myObject['1'] = 'o';
myObject['2'] = 'o';
console.log(myObject); // Logs Object { 0="f", 1="o", 2="o"}
var myString = new String('foo'); // Produces a String() object.
console.log(myString); // Logs foo { 0="f", 1="o", 2="o"
Please explain.
Upvotes: 0
Views: 96
Reputation: 3627
It's completely normal behavior:
new String
creates an Object
, if you will type "var myString = new String('moo')"
, you will get another object with different values.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/#section_7
Upvotes: 0
Reputation: 943694
if its a new instance how does it carry the value of myObject onto myString variable
It doesn't. You are initialising your String object with a string literal:
new String('foo');
That foo is an entirely different foo to the characters you assign to the three properties of the object. For comparison, replace the second foo with bar.
Upvotes: 1