Mar 6, 2010

how to test whether a object has member

Object.prototype.hasMember = function (memberName)
  {
    return memberName in this;

}
  
var attrFn = {
    val: 1,
    css: 2,
    html: 3,
    text: 4,
    data: 5,
    width: 6,
    height: 7,
    offset: 8
  };
  
alert(attrFn.hasMember("val"));

/*
don't use attrFn["val"], because is possible that you defined a member
attFn = { val : undefined }, in val is a member but its value is null,
this function also traverse the prototype chain, if you want to check direct member only use "hasOwnProperty".
*/