I'm not very fortable with objects yet and this is my first Stack Overflow question so bear with me. Using the following code,
function wrap(value) {
return {
"value": value
};
}
var obj = new wrap("Hello");
obj.value
equals "Hello".
Why does this work? It looks to me as if wrap()
is returning an object not associated with the variable obj
, so obj.value
should not equal Hello
.
How is the object that is returned assigned to the variable obj
? Does obj
automatically equal {"value": value}
because it is wrapped inside wrap()
?
I'm not very fortable with objects yet and this is my first Stack Overflow question so bear with me. Using the following code,
function wrap(value) {
return {
"value": value
};
}
var obj = new wrap("Hello");
obj.value
equals "Hello".
Why does this work? It looks to me as if wrap()
is returning an object not associated with the variable obj
, so obj.value
should not equal Hello
.
How is the object that is returned assigned to the variable obj
? Does obj
automatically equal {"value": value}
because it is wrapped inside wrap()
?
-
1
you don't need to use
new
whenreturn
ing a literal. obj will be whatever the function returns. – dandavis Commented Apr 7, 2015 at 22:11
4 Answers
Reset to default 4You are essentially doing the same thing as
var obj = {value: "Hello"};
In which case, the following is true
obj.value == "Hello"
The fact that you're assigning through a function doesn't change anything in this example.
The new
operator does two things:
- Binds
this
to a new, empty object - Returns
this
at the end of the function if no return statement is reached (as opposed toundefined
)
But your function has a return statement, which returns the object { value: value }
, so you will get that object. This is the same as if you called var obj = wrap("Hello");
.
To show the significance of new
, if your function was:
function wrap (value) {
this.value = value;
}
calling var obj = new wrap("Hello")
would give the same result (an object with the key value
storing "Hello"
), while calling var obj = wrap("Hello")
would store "Hello" in the key value
on the global context (the window, in the browser) and undefined
in the variable obj
.
when you call function using new
keyword this
is returned unless returned value is specefied like your code:
so
var obj = new wrap("Hello");
will get the value of:
{
"value": "Hello"
};
because it is passed as an argument so:
obj.value=="hello" //true
you trait warp() as type (class) and you instantiate an object by new key work but you return object
you create object of wrap() with new keyword but you return object of value;
try:
function foo( value ) {
function bar( x,y ) { return x+y; }
return { sum: bar, value: value }
}
var obj = new foo("hello");
obj.value == "hello" // true
obj.sum(3,4) // == 7
your object can still referring to the inner wrap() with new key word