简体   繁体   中英

ES6 class setter as a function

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(); } 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.

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.

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM