I was curious if I can make an object method look and act like an
object property.
example:
function Circle(x,y,r){ this.x = x; this.y = y; this.r = r; }
Circle.prototype.area = function(){ return Math.PI * this.r * this.r; }
var c = new Circle(0,0,1);
I would like to get the area by calling it: var area = c.area;
instead of c.area();
well you can emulate a getter property if you modify the function toString
return
(works with MS JScript and SpiderMonkey JavaScript)
Object.prototype.addProperty = function( /*String*/ name, /*Function*/
getter, /*Function*/ setter )
{
var self = this;
if( setter == null )
{
setter = function() {};
}
this[name] = function()
{
if( arguments.length == 0 )
{
return getter.call( self );
}
else
{
setter.apply( self, arguments );
}
}
this[name].toString = function()
{
return getter.call( self );
}
}
//usage (note: the trace function is whatever document.write/printf/etc. you
want)
toto = {};
toto.getA = function()
{
return this._a;
}
toto.setA = function( value )
{
this._a = value;
}
toto.addProperty( "a", toto.getA, toto.setA );
trace( toto.a() ); //undefined
trace( toto.a ); //undefined
toto.a( "hello world" );
trace( toto.a() ); //"hello world"
trace( toto.a ); //"hello world"
//other usage
titi = function()
{
this._a = 1234;
this._b = null;
var _c = "secret";
this.getC = function()
{
return _c;
}
this.addProperty( "a", this.getA, null );
this.addProperty( "b", this.getB, this.setB );
this.addProperty( "c", this.getC, null );
}
titi.prototype.getA = function()
{
return this._a;
}
titi.prototype.getB = function()
{
return this._b;
}
titi.prototype.setB = function( value )
{
this._b = value;
}
foobar = new titi();
trace( foobar.c ); //"secret"
foobar.c( 567989 );
trace( foobar.c ); //"secret"
--------------------------
for your example:
Circle = function( /*Int*/ x, /*Int*/ y, /*Int*/ r )
{
this.x = x;
this.y = y;
this.r = r;
this.addProperty( "area", this.getArea, null );
}
Circle.prototype.getArea = function()
{
return Math.PI * this.r * this.r;
}
var c = new Circle(0,0,1);
trace( c.area ); //3.14159265358979
c.r = 50;
trace( c.area ); //7853.98163397448
I would like to get the area by calling it: var area = c.area;
done
zwetan