If I wanted to support assignment of object properties using fluent function chaining. E.g., something like:
foo.width(500).height(250).margin({left:5,right:10});
I could obviously create a function definition like:
margin(value) {
this.config.margin = value;
return this;
}
But what if I wanted to be able to support the above function chaining but also direct assignment like:
foo.margin = {left:5,right:10};
I could add this support by adding a setter like:
set margin(value) {
this.config.margin = value;
}
But you can't have a setter and a function that go by the same name and apparently the setter only works with the literal assignment operation and the function definition only works with the fluent API approach.
Is there a way to have both in a syntactically graceful way with JS ES6?
I've included a fiddle which demonstrates a working example of both fluent and literal assignment operators. The only problem? I've had to resort to using different naming signature which increases the API surface ... if possible I'd like to avoid this.
http://www.es6fiddle.com/i6o0jscx/
If you're willing to use an extra two characters to retrieve the property values, then you can do this:
export class Foo {
constructor() {
this.config = {
width:500,
height: 400
};
}
get width() {
return function(value) {
if (arguments.length) {
this.config.width = value;
return this;
}
return this.config.width;
};
}
set width(value) {
this.config.width = value;
}
}
let foo = new Foo();
console.log(foo.width());
foo.width = 600;
console.log(foo.width());
console.log(foo.width(250).width());
Basically, the getter returns a function that sets the value if it is called with arguments, or returns the value if it is called without arguments. This is similar to the API jQuery provides for .text() and .html() and a lot of other things, but it gives you the additional option of assigning directly to the property. I wouldn't really recommend this because it's confusing to be able to do foo.width = 5; but not var w = foo.width;, but I can't see a good way to fully achieve what you're trying to do.
http://www.es6fiddle.com/i6o14n4b/
You can have both. You just have to stick to the naming conventions:
class Thing {
constructor() {
this._property = 0;
}
get property() {
return this._property;
}
setProperty(property) {
this.property = property;
return this;
}
set property(property) {
this.setProperty(property);
}
}
This way you can have the cake and eat it too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With