Reputation: 3913
I googled a bit and it seems I either don't know what I'm asking or this isn't possible. I think it's probably the former.
If I have an object
obj = {
func : function(){
return 'hello';
}
}
and I normally do alert(obj.func())
I of course get "hello"
But if I wanted to have obj.func
be simply a variable, is that possible somehow? I won't ever pass parameters to the function, I just want to reference its return value as a plain variable like alert(obj.func)
, not a function call.
Thanks.
Upvotes: 1
Views: 2997
Reputation: 19294
What you are talking about is a getter : it is a function that works as a property.
It is standard since javascript 1.8.5, which means older browser won't handle it.
The syntax is as follow, using your example :
obj = {
get func() { return "hello" ; }
};
// use like this :
console.log(obj.func);
Most likely you will want to define a setter also : this is also a function behaving like a property. The syntax will be :
obj = {
get func() { return this._innerText ; },
set func(txt) { this._innerText = txt ; },
_innerText : "hello"
};
console.log(obj.func) ; // output is hello
obj.func = "godd bye" ;
console.log(obj.func) ; // output is good bye
Obviously, as often with simple example, this one is of no big use:
Let us see a degree to radian converter using a getter / setter :
var Angle = {
get degree () { return this._degree ; },
set degree (dg) { this._degree = dg ; },
get radian () { return 2*Math.PI*this.degree/360 ; },
set radian (rd) { this._degree = rd * 360 / (2*Math.PI) ; },
_degree : 0
} ;
// you can use :
Angle.radian = Math.PI / 2;
console.log ( Angle.degree ); // -->> output is 90
Angle.degree=45 ;
console.log(Angle.radian) ; // --> output is 0.7853... which is PI/4
You might also have a look on Object.defineProperty, which allows to define both standard properties, and getters/setters, but with more option, especially the option to 'hide' a property, which allows it not to be enumerated.
For more information :
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/get
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/set
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty
Upvotes: 2