Reputation: 207
I have below javascript function-
function ResponseVal()
{
this.value1;
this.value2;
}
var Response = new ResponseVal();
I tried and execute above code in chrome consolebar.I could not understand why newly created object "Response" does not show property value1 and value2. Can anyone help me to understand it what is happening and why properties are not displaying.
Upvotes: 3
Views: 2087
Reputation: 4193
Declaring a property without setting it essentially does nothing. While it won't result in an error, some interpreters will throw a warning—as will strict mode, I believe.
JavaScript doesn't make this immediately obvious. For example, if you do this:
function Hello() {
this.value1;
}
var h = new Hello;
alert(h.value1);
The alert will read undefined
. However, the property value1
was never actually accessed—it doesn't exist at all because you did not provide a value for it.
Rather than throwing an error, JavaScript returns undefined
any time you try to access a property that doesn't exist. So you will get the same result if you write, say:
alert(h.property_that_doesnt_exist); //alerts 'undefined'
Iterating through the properties of h
shows clearly that the property value1
does not exist:
for (var key in h) {
alert(key + ' = ' + h[key]);
}
This alerts nothing, because no properties will be found. However, if you set the property to the JS primitive undefined
, the property WILL exist:
function Hello() {
this.value1 = undefined;
}
var h = new Hello;
for (var key in h) {
alert(key + ' = ' + h[key]); //alerts 'undefined'
}
You can run the above code here: http://jsfiddle.net/Acdmn/
But there's no good reason to set a property/variable to undefined
. To create a property with an "empty" value, JavaScript programmers typically use null
:
function Hello() {
this.value1 = null;
}
This makes it clear that the property was created intentionally, but you're not ready to give it a meaningful value yet.
Lastly, note that property definitions work differently from "normal" (private) variables explicitly set with var
(even though these are also properties, in this case of the window
object). If you write:
var foo;
alert(foo);
alert(some_undefined_variable_name);
The first alert will say undefined
. The variable foo
was created, does exist, and contains the primitive value undefined
(even though you didn't set it explicitly). The second alert, however, will throw a reference error:
ReferenceError: some_undefined_variable_name is not defined
So JavaScript is unforgiving about using undefined variables, but it doesn't care if you try to use an undefined property.
Upvotes: 0
Reputation: 9858
You should set the values to something. All you've done is try to read them in the constructor.
function ResponseVal()
{
this.value1 = "";
this.value2 = "";
}
var Response = new ResponseVal();
Upvotes: 4