4 ms·
It's also impossible to instantiate an object with `new` and varargs. new Breakfast('bacon', 'eggs') // great new Breakfast.apply(null, ['bacon', 'eggs
by jayferd 15y ago
It's also impossible to instantiate an object with `new` and varargs.
new Breakfast('bacon', 'eggs') // great
new Breakfast.apply(null, ['bacon', 'eggs']) // b0rk
- jashkenas 15y agoCoffeeScript has to bend over backwards to allow this, but it does... foods = ['bacon', 'eggs', 'toast'] new Breakfast foods...
- spicyj 15y agoI just stumbled across this interesting SO answer: http://stackoverflow.com/a/3362623/49485 http://stackoverflow.com/a/3362623/49485
- eldude 15y agoThis works: var a = new (Breakfast.bind.apply(Breakfast, [null, 'bacon', 'eggs'])) a instanceof Breakfast // true Or... var a = new (Function.bind.apply(Breakfast, [null].concat(['bacon', 'eggs']))) a instanceof Breakfast // true UPDATE (for kicks): Or... (works with Crockford's Object.create) var a = Object.create(Breakfast.prototype); Breakfast.apply(a, ['bacon', 'eggs']); a instanceof Breakfast // true
- firefoxman1 15y agoVery cool. Bind is a much-appreciated addition to the language.
- prodigal_erik 15y agoUnfortunately it wasn't there from day one. It was only specified a year or two ago (thus IE 8 and Opera 11.50 didn't have it, and apparently Safari 5.1 still doesn't) so you have to be prepared to check for it and roll your own. http://kangax.github.com/es5-compat-table/ http://kangax.github.com/es5-compat-table/
- jayferd 15y agoAwesome. I do notice a gigantic warning on MDN to not rely on this behavior, though: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#section_9 https://developer.mozilla.org/en/JavaScript/Reference/Global... In p.js (github.com/jayferd/pjs), I used this pattern/workaround: var Breakfast = function(args) { if (!(this instanceof Breakfast)) return new Breakfast(arguments); if (args && typeof this.init === 'function') this.init.apply(this, args); } So these would be equivalent: Breakfast('bacon', 'eggs') new Breakfast(['bacon', 'eggs']) Whereas `new Breakfast` would return an "uninitialized" object as in Object.create.
- eldude 15y agoI used a similar pattern once, except _generically_ as follows: function Breakfast(my, args) { if (!(this instanceof arguments.callee)) return new arguments.callee(arguments); if (Object.prototype.toString.call(arguments[0]) === '[object Arguments]') arguments.callee.apply(this, args); }