Reputation: 53
I'm trying to submit the setter function of a class as a parameter.
Let's asume there is:
class A {
set foo(foo) {
this._foo = foo
}
}
However, if I'm calling the function f(setter) { setter(); }
like this f(obj.foo)
, of course the value of obj.foo
will be submitted calling the getter.
I was thinking about using an arrow function (foo) => obj.foo = foo
and it works. But there must be a shorter way, something like f(obj.setFoo)
to get the setter function.
Ideas are welcome.
Upvotes: 1
Views: 754
Reputation: 288060
You can always define a getter which returns the setter:
class A {
get foo() {
return Object.getOwnPropertyDescriptor(A.prototype, 'foo').set;
}
set foo(foo) {
this._foo = foo;
}
}
var obj = new A();
(function(setter) {
setter.call(obj, 123);
console.log(obj._foo); // 123
})(obj.foo);
Upvotes: 1
Reputation: 344537
But there must be a shorter way, something like f(obj.setFoo) to get the setter function.
Nope. There's a longer way,
var setFoo = Object.getOwnPropertyDescriptor(obj, 'foo').set;
setFoo.call(obj, 'bar');
Accessor functions are stored in the internal property attributes and are not accessible without using reflection. Stick with your arrow function solution or define getter/setter functions (instead of an accessor property) on the class.
Upvotes: 1