Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's also impossible to instantiate an object with `new` and varargs.

    new Breakfast('bacon', 'eggs') // great
    new Breakfast.apply(null, ['bacon', 'eggs']) // b0rk


CoffeeScript has to bend over backwards to allow this, but it does...

    foods = ['bacon', 'eggs', 'toast']

    new Breakfast foods...


This 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


Awesome. I do notice a gigantic warning on MDN to not rely on this behavior, though: 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.


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


Very cool. Bind is a much-appreciated addition to the language.


Unfortunately 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/


I just stumbled across this interesting SO answer:

http://stackoverflow.com/a/3362623/49485




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: