views:

27

answers:

1

I'm trying to find a way to to property overloading like it's done in PHP: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

i.e.

var myobj = function () {}
myobj.prototype.getProperty = function (propertyName) { console.log('Property Requested: ', propertyName); }

var otherObj = function () {};

myobj.hello; // Property Request: hello
otherObj.hello; // undefined

Is this possible?

A: 

This sort of thing can only be done in ECMAscript 5 which is not supported in all browsers (e.g. IE). Using Object.defineProperty you can create properties with accessor functions - so you could implement a property like length in arrays that varies, depending on the object state.

There's a good presentation from Doug Crockford about these features and with links to more detailed descriptions here.

andrewmu