5 ms·
It's to avoid using "new".
by jwmerrill 12y ago
It's to avoid using "new".
- aikah 12y ago> It's to avoid using "new". yeah,well one is still using new inside the constructor. it's pretty obvious to me that : 1/ one should read the docs before using an api 2/ capitalized functions are meant to be used as constructors. 3/ If you dont like this pattern,write builders and make them obvious. like Object.create() To me when i design js APIs, I have 2 kind of "templates" : the jQuery "$(o).after(b).get(0)"/underscore "_(object).method().value()" monadic api style that wraps types (like promises) OR The way the DOM is built,more java-ish with builders everywhere ( document.createElement ... ). So I hardly use new anymore. I get that people might make mistake or like Python style OO;but still, I think forcing the "new" in unecessary.
- iLoch 12y agoCant you just "return this;" to avoid using "new"?
- aikah 12y ago> Cant you just "return this;" to avoid using "new"? THIS will be the global scope if a function meant to be a constructor is called without new. Try that in your console function Foo(){this.foo = "bar";return this} then do : Foo() ; it will return window; so the answer is no.
- greg5green 12y agoThe answer is yes if you do: Foo.call({});
- LazerBear 12y agoThat's a cool trick, though 'instanceof' won't work in this case.
- cygx 12y agoYup. The proper way to emulate new is Foo.call(Object.create(Foo.prototype))
- LazerBear 12y agoDouglas Crockford, is that you? Oh the lengths people will go to avoid using 'new'... I wonder if any linters out there warn when they see something like: something = SomeCapitalizedFunction() Because forgetting to use 'new' is really the only thing I could think of that makes this pattern dangerous.
- hderms 12y agowhy do people want to avoid using new?
- LazerBear 12y agoIf you accidentally forget to use 'new' when you're supposed to, the "constructor" method will change the global object instead of a new object, it can cause strange behavior that is very hard to trace.
- hderms 12y agoAh, I see. I guess I've never forgotten to use new. That does sound incredibly annoying to debug.