Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 525293
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T08:39:23+00:00 2026-05-13T08:39:23+00:00

A nasty gotcha in javascript is forgetting to call new on a function meant

  • 0

A nasty gotcha in javascript is forgetting to call new on a function meant to be instantiated, leading to this being bound to a different object (usually the global) instead of a fresh one. One workaround I read about is to check for it explicitly in the function-constructor using the following idiom:

function SomeConstructor(x, y, ...) {
    // check if `this` is created with new
    if ( !(this instanceof arguments.callee) )
        return new SomeConstructor(x, y, ...);
    // normal initialization code follows

Now new SomeConstructor(...) and SomeConstructor(...) are equivalent.

I’d like to simplify this by creating a wrapper function factory(fn) that does the first two lines and then delegates to the wrapped function fn. This would be used like:

SomeConstructor = factory(function (x, y, ...) {
    // normal initialization code follows
})

My first attempt was:

function factory(fn) {
  return function() {
    if ( !(this instanceof arguments.callee) ) {
      return new arguments.callee.apply(this, arguments);
    }
    fn.apply(this, arguments);
  }
}

but it fails with “Function.prototype.apply called on incompatible [object Object]”. The second attempt was:

function factory(fn) {
  return function() {
    if ( !(this instanceof arguments.callee) ) {
      var tmp = new arguments.callee();
      arguments.callee.apply(tmp, arguments);
      return tmp;
    }
    fn.apply(this, arguments);
  }
}

This sort of works but it may call the wrapped function twice: once with no arguments (to create a new instance) and once with the passed arguments for the actual initialization. Apparently this is fragile and inefficient but I can’t figure out a way to do it with a single call. Is this possible ?

EDIT: Based on bobince’s approach, here’s a similar one that does the trick:

function factory(init) {
    var run_init = true;
    function constr() {
        if ( !(this instanceof constr) ) {
            run_init = false;
            var tmp = new constr();
            run_init = true;
            init.apply(tmp, arguments);
            return tmp;
        }
    if (run_init)
        init.apply(this, arguments);
  }
  return constr;
}

As for whether this is something that should be encouraged or not, that’s debatable. I come from a Python background and I think of new as just noise (Java) or wart (Javascript), but I may be missing something.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T08:39:23+00:00Added an answer on May 13, 2026 at 8:39 am

    You can pass a unique value into the constructor for the first call (with new) that signifies you don’t want the initialiser called yet:

    var _NOINIT= {};
    function factory(init) {
        function constr() {
            if (!(this instanceof constr)) {
                var inst= new constr(_NOINIT);
                init.apply(inst, arguments);
                return inst;
            }
            if (arguments[0]!==_NOINIT)
                init.apply(this, arguments);
        }
        return constr;
    }
    

    Note I’ve used a named inline function for the constructor because arguments.callee will be going away in ECMAScript Fifth Edition’s ‘strict’ mode.

    However if you’re using a class factory, I suggest making the initialiser function a member of the class, rather than being passed in. That way, you can subclass a base class and have the subclass inherit the initialiser, which is normal behaviour in class-based languages. eg.:

    Function.prototype.makeSubclass= function() {
        function constr() {
            var that= this;
            if (!(this instanceof constr))
                that= new constr(_NOINIT);
            if (arguments[0]!==_NOINIT && '_init' in that)
                that._init.apply(that, arguments);
            return that;
        }
    
        if (this!==Object)
            constr.prototype= new this(_NOINIT);
        return constr;
    };
    
    var Shape= Object.makeSubclass();
    Shape.prototype._init= function(x, y) {
        this.x= x;
        this.y= y;
    };
    
    var Point= Shape.makeSubclass();
    // inherits initialiser(x, y), as no need for anything else in there
    
    var Circle= Shape.makeSubclass()
    Circle.prototype._init= function(x, y, r) {
        Shape.prototype._init.call(this, x, y);
        this.r= r;
    };
    

    Of course you don’t have to put that into the Function prototype… it’s a matter of taste, really. As is allowing constructors without new.

    Personally I prefer to throw an error rather than silently make it work, to try to discourage bare-constructor-calling, since this is a mistake elsewhere and may make the code slightly less clear.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 265k
  • Answers 265k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Like it says, you cannot initialize static non-integral types in… May 13, 2026 at 12:21 pm
  • Editorial Team
    Editorial Team added an answer Assuming your config file is in the installation program (it… May 13, 2026 at 12:21 pm
  • Editorial Team
    Editorial Team added an answer Open your model as XML. Remove all references to that… May 13, 2026 at 12:21 pm

Related Questions

I've been working in Silverlight recently and I've slowly been discovering that as simple
I need to queue events and tasks for external systems in a reliable/transactional way.
This is a nasty one for me... I'm a PHP guy working in Java
So I have a nasty stack overflow I have been trying to track down
I had a nasty typo that wasted my time and my colleague's time, it

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.