Define static properties and prototype properties with the class syntax

Glen Huang curvedmark at gmail.com
Sat Dec 13 03:03:57 PST 2014


After thinking about it, I think you are right. Defining this defaults property is almost like defining a global variable, that modifying it might affect lots of objects are created with the constructor.

It’s probably a good thing that class syntax doesn’t support it, but I reckon a lot of jquery plugin authors would do “class Foo {}; Foo.defaults = {};” nonetheless.

> On Dec 13, 2014, at 6:53 PM, Frankie Bagnardi <f.bagnardi at gmail.com> wrote:
> 
> It's an antipattern to modify things you didn't create, and jQuery is the embodiment of this antipattern :-)
> 
> If you really need to do this, you should also put a comment saying "Modify Menu.defaults to change the default settings".  And put it in any docs that go with it.
> 
> 
> 
> On Sat, Dec 13, 2014 at 3:35 AM, Glen Huang <curvedmark at gmail.com <mailto:curvedmark at gmail.com>> wrote:
> Thanks for the sample code.
> 
> But the defaults actually contains other properties like width, height, etc that let users customize the constructed menu object. So subclass won’t work here.
> 
> A lot jquery plugin are actually written this way:
> 
> http://learn.jquery.com/plugins/advanced-plugin-concepts/ <http://learn.jquery.com/plugins/advanced-plugin-concepts/>
> 
> Look at the first example, A defaults property is attatched to the constructor.
> 
>> On Dec 13, 2014, at 6:20 PM, Frankie Bagnardi <f.bagnardi at gmail.com <mailto:f.bagnardi at gmail.com>> wrote:
>> 
>> You're much better off subclassing menu for that purpose.
>> 
>> class Menu
>>     constructor(options) {
>>         this.options = Object.assign({hidden: false}, options);
>>     }
>> }
>> 
>> class HiddenMenu extends Menu {
>>     constructor(options){
>>         super(Object.assign({hidden: true}, options));
>>     }
>> }
>> 
>> 
>> On Sat, Dec 13, 2014 at 2:54 AM, Glen Huang <curvedmark at gmail.com <mailto:curvedmark at gmail.com>> wrote:
>> But allowing getter & setter already makes it dangerous:
>> 
>> let _bar = {}
>> class Foo {
>>         static get bar() { return _bar; }
>> }
>> 
>> Objects that have Foo.prototype in the prototype chain can do "this.bar.a = 1", and the change won’t be shadowed.
>> 
>> I found myself looking for a way to define static properties because I want to do this:
>> 
>> function Menu(options) {
>>         this.options = Object.assign({}, Menu.defaults, options);
>> }
>> Menu.defaults = { hidden: false };
>> 
>> I want to expose the defaults property so it can be modified by users. This pattern is very ubiquitous in es5. I wonder if the class syntax could allow this pattern to be carried to es6?
>> 
> 
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141213/7bcc94fb/attachment.html>


More information about the es-discuss mailing list