问题描述:

Can i add some functional to the object, which will return default value when accessing a undefined object property?

For example something like this:

var obj = {

a:1,

b:2,

// can i add some functional here, which

// will return default value

// when accessing a missing property

// for example "property "+prop+" missing in obj"?

}

alert(obj.c) // "property c missing in obj"

is it any way to do it?

网友答案:

What you want are JavaScript proxies. However, browser support for them is weak.

If you expect your program to run on all modern browsers, you shouldn't use proxies; however, if you're using JavaScript server-side or in an otherwise constricted environment, it is an option. I think that Node.js, for example, supports them (although I could be wrong on this).

If you are working on cross-browser code, then I do not know of any neat way to implement the functionality you want.

网友答案:

Try this:

alert((obj.c!=undefined)?obj.c:"Undefined");

To actually answer your question, you should never be looking for a property or method of an object that doesn't exist. If you happen to be looping through an objects properties you [] notation instead of dot notation such as.

var x, obj = {...}

for(x in obj){
  alert("Property name:"+x+" | value: "+obj[x]);
}

furthermore you can always wrap whatever statement that is questionable in a try/catch.

or function instead of object literal:

var obj = function(Params){
    this.URL = "";
    this.QueryString = new Array();
    this.Params = Params;
    this.Method = "POST";
    this.CallBack = "";
    this.OnSuccess = "";
    this.OnFailure = "";
    this.Header = "application/x-www-form-urlencoded";
    this.Response = "";

    for(var Param in this.Params){
         switch (Param){
           case 'URL' : this.URL = this.Params[Param]; break;
           case 'QueryString' : this.QueryString = this.Params[Param];break;
           case 'Header' : this.Header = this.Params[Param]; break;
           case 'Method' : this.Method = this.Params[Param]; break;
           case 'CallBack': this.CallBack = this.Params[Param]; break;
           case 'OnSuccess': this.OnSuccess = this.Params[Param]; break;
           case 'OnFailure': this.OnFailure = this.Params[Param]; break;
               case default: something(); break; //I just don't have this line because I didn't need a default;
         }
    }

}

The above was the beginning to an ajax object I wrote, but you get the idea..

相关阅读:
Top