javascript object properties is not displaying -


i have below javascript function-

function responseval() {     this.value1;     this.value2; }    var response = new responseval(); 

i tried , execute above code in chrome consolebar.i not understand why newly created object "response" not show property value1 , value2. can me understand happening , why properties not displaying.

declaring property without setting nothing. while won't result in error, interpreters throw warning—as strict mode, believe.

javascript doesn't make obvious. example, if this:

function hello() {      this.value1; }  var h = new hello; alert(h.value1); 

the alert read undefined. however, property value1 never accessed—it doesn't exist @ because did not provide value it.

rather throwing error, javascript returns undefined time try access property doesn't exist. same result if write, say:

alert(h.property_that_doesnt_exist);   //alerts 'undefined' 

iterating through properties of h shows property value1 not exist:

for (var key in h) {     alert(key + ' = ' + h[key]); } 

this alerts nothing, because no properties found. however, if set property js primitive undefined, property exist:

function hello() {      this.value1 = undefined; }  var h = new hello;  (var key in h) {     alert(key + ' = ' + h[key]);  //alerts 'undefined' } 

you can run above code here: http://jsfiddle.net/acdmn/


but there's no reason set property/variable undefined. create property "empty" value, javascript programmers typically use null:

function hello() {      this.value1 = null; } 

this makes clear property created intentionally, you're not ready give meaningful value yet.


lastly, note property definitions work differently "normal" (private) variables explicitly set var (even though these properties, in case of window object). if write:

var foo; alert(foo); alert(some_undefined_variable_name); 

the first alert undefined. variable foo was created, exist, , contains primitive value undefined (even though didn't set explicitly). second alert, however, throw reference error:

referenceerror: some_undefined_variable_name not defined 

so javascript unforgiving using undefined variables, doesn't care if try use undefined property.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -