javascript - How to return a default property of JS literal object? -


one js object defined this:

var obj = {       key1 : {on:'value1', off:'value2'},       key2 : {on:'value3', off:'value4'} } 

is there tricky way, pick default key1 'on' property, when obj.key1 passed without property?

var key1state = obj.key1; // want receive 'value1' here, not obj.key1{...} 

is somehow possible recognize in object definition body property (if @ all) passed/asked during object call?

i'm not sure if need, messing valueof or tostring may you're looking for.

for example:

var obj = {       key1 : {on:'value1', off:'value2', tostring : function(){ return this.on; }},       key2 : {on:'value3', off:'value4', tostring : function(){ return this.on; }} }  var key1state = obj.key1; // object var key1statestr = '' + obj.key1; // string "value1" obj.key1 == "value1"  // true obj.key1.tostring() === "value1"  // true 

so if going use default value string somewhere may useful.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -