Javascript new keyword - code explanation request - javascript

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.

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.

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/#se‌​ction_7

Related

Need help understanding how these TypeScript declarations are different

Trying to understand the differences between these declarations:
let foo = new String('bar'); // StringConstructor
let foo = new Number(100); // NumberConstructor
let foo: String = 'bar'; // interface
let foo: Number = 100; // interface
var foo: string = 'bar'; // globally scoped?
var foo: number = 100; // globally scoped?
Are there any particular pros and cons to using different declarations over others?
JavaScript's primitive String is immutable, which is a huge difference between passing an object (created with new), vs passing the primitive (myVar = 'my-value';).
For example, try something like:
var myObject = new String('my value');
var myPrimitive = 'my value';
function myFunc(x) {
x.mutation = 'my other value';
}
myFunc(myObject);
myFunc(myPrimitive);
console.log('myObject.mutation:', myObject.mutation);
console.log('myPrimitive.mutation:', myPrimitive.mutation);
Which should output:
myObject.mutation: my other value
myPrimitive.mutation: undefined
Note that the same applies to TypeScript, and to Number type as well.
let/var are not related to Typescript, they are related to Javascript:
What's the difference between using "let" and "var"?
String created by calling "new String()" is typeof object and you should avoid it.
In second and third cases, "String" is Javascript object used for creating strings, "string" is typescript type which should be used for typing string variable.

JavaScript object array

I have the following code snippet below:
var obj = new Object();
var foo = new Object();
var bar = new Object();
obj[foo] = 'hello';
obj[bar] = 'hi'
console.log (obj[foo])
It prints "hi". Why is this?
Objects in JS can have string keys only. When you do obj[foo] actualy you do obj[foo.toString()].
Your code will be
obj["[object Object]"] = 'hello';
obj["[object Object]"] = 'hi'
console.log (obj["[object Object]"])
Objects need a string as reference. Any variable used as key is casted to string with the prototype toString and here you get for this '[object Object]', which is used as key.
var obj = new Object(),
foo = new Object(),
bar = new Object();
obj[foo] = 'hello';
obj[bar] = 'hi'
console.log (obj[foo]);
console.log('' + foo); // force object to use toString() method
console.log (obj['[object Object]']);
you are assigning the object obj with keys which are objects (foo & bar).
When keys given to object are objects themselves then the following is assigned as the key value
[object Object]
this simply means that your 1st assignment
obj[foo] = 'hello'
created key [object Object] and made its value "hello";
then your second assignment did the same, but since the key [object Object] is already present, the previous value got overridden with "hi".
Now when you try to access the property of obj with foo or bar or any other object, you are actually doing
obj["[object Object]"]
You're defining foo as an object, and bar as an object. When you assign them to the original object (obj), you're basically saying this:
obj["Object"] = 'hello';
obj["Object"] = 'hi';
console.log(obj["Object"]); //Will be the last object.
Keys need to be string types. If they're not a string, they will be converted to a string. In the cast of Object() to a string, they'll be turned into [object Object]. Check out this answer for an alternatitve way to override toString()'s functionality to return the object's name, or a unique identifer for the key you're trying to create.
To see this in action, let's do this:
var obj = new Object();
var foo = new Object();
var bar = new Object();
obj[foo] = 'hello';
console.log(obj);
/* Shows:
{
"[object Object]": "hello"
}
*/
obj[bar] = 'hi';
console.log(obj);
/* Shows:
{
"[object Object]": "hi"
}
*/
console.log(obj[foo]); //Will show hi
console.log(obj['[object Object]']); //Essentially the same thing
I have not used the new object constructor on javascript yet, since it is not my preferred language, but the mistake is most likely obvious, you have not assigned anything on your "foo" and "bar" variables, so regardless, their values will be the same, which is the initial value upon declaration of the object without any assignment. What's happening is you are assigning second value on top of your first, which applies to the "obj" array's element.
You are using objects as property-names in your object obj. Property names are strings, therefore your objects are stringified to [object Object]. As both objects are stringified to the same name, bar replaces foo.
The result looks like this:
{
"[object Object]": "hi"
}

Javascript: Can a string be cast as/converted to a type constant?

If I have a variable containing a string, is there a way that I can treat the contents of that string as the name of a type?
For example, is there a ???? in Javascript such that:
var ts = "Array";
var magic_type = ????; //magic
var obj_instance = new magic_type;
is valid and obj_instance == [] ?
You can instantiate it by using bracket notation with the global object.
var arr = new window['Array'];
jsFiddle.
If the constructor takes arguments, add them to the end.
As a side note, your code example...
obj_instance === []
...won't ever evaluate to true because the [] syntax will create a new Array with a different memory location.
var instance = new window[someString]();
No magic required.

How to determine whether an object was created using an object literal or an Object constructor call?

More specifically, how would you determine if a certain object was created using a literal or not?
var s1 = new String();
var s2 = ""; // Literal
var o1 = new Object();
var o2 = {}; // Literal
var f1 = new Function();
var f2 = function(){}; // Literal
Obviously if you compare any two above, for example:
var o1 = new Object();
var o2 = {};
alert(o1 == o2);
alert(o1 === o2);
alert(typeof o1);
alert(typeof o2);
... The first two alerts will show false while the last two alerts will give [Object object]
Say for example, if I wanted to do this:
function isLiteral(obj, type) {
// ...
}
... how would one go about doing this?
I have taken a look at How to determine if an object is an object literal in Javascript?, but it does not answer my question.
Firstly, the difference between these two lines:
var s1 = new String();
var s2 = ""; // Literal
...and the difference between these two lines:
var o1 = new Object();
var o2 = {}; // Literal
...are two different concepts.
The first is the difference between a primitive value and an object, while the second is... different syntax for the same thing.
Strings, numbers and booleans are primitive values, not objects, but can be wrapped as objects using new String(), new Number() or new Boolean(). So for these, typeof will return different values:
var s1 = new String();
typeof s1; // "object"
var s2 = "";
typeof s2; // "string"
However, for Object and Function, the difference between:
var o1 = new Object();
var o2 = {};
... is in syntax only.
Both o1 and o2 have the same prototype, and the same constructor, making them indistinguishable at runtime.

diffrerent ways to create object in javascript

What is the differnce between following two?
obj = new Object();
OR
obj = {};
In my code am asked to replace first notation with second one and the code is huge.Will replacing it cause any problem?
According to JavaScript Patterns book, using a built-in constructor (obj = new Object();) is an anti pattern for several reasons:
it's longer to type than literal (obj = {};)
literal is preferred because it emphasizes that objects are mutable hashes
scope resolution - possibility that you have created your own (local) constructor with the same name (interpreter needs to look up the scope chain)
I will answer the second question:
Will replacing it cause any problem?
Nope, it won't cause any problem.
If you have for example those lines:
var obj = new Object("a");
//...code...
obj = new Object("b");
//...code...
Changing to this will have same result and no impacts:
var obj = { "a": 1 };
//...code...
obj = { "b": 2 };
//...code...
By assigning the variable with the = you're overwriting whatever it contained with the new value.
There is no difference. The former uses the Object constructor, whereas the latter is a literal, but there will be no difference in the resulting objects.
Greetings
Objects in JavaScript
1- var obj = { key1 : value1 , key2Asfunction : funciton1(){} };
obj.key1;
obj.key2Asfunction();
2- var obj = function()
{
this.obj1 = value1 ;
this.function1 = function(){};
}
var ob = new obj();
ob.obj1;
ob.function1();
if you need how to create the structure of the jquery frame work too i can help
Regrads :)

Categories

Resources