Reputation: 2162
When I perform some tests I need to declare an object with several properties, usually equal to a dummy function/value.
In Python there is the possibility to define, through the method __get__
the function invoked when accessing to an object property, so that the property can be computed at runtime.
There is the same possibility in Javascript or some workaround?
What I want to do is to have an Object x
where x[whatever_it_is]
is equal to a value defined by me.
Upvotes: 0
Views: 51
Reputation: 69
You could use Proxies to imitate __get__
using handlers with a get
trap:
var handler = {
get:: function(obj, prop) {
// return some value here
if (prop === "name")
return "Foo"
return obj.prop
}
}
var proxy = new Proxy(dummyObj, handler)
console.log(proxy.name) // => Foo
Upvotes: 2
Reputation: 258
setters in javascript or Proxy in javascript or getters can help to solve your task.
Upvotes: 2