Search code examples
javascriptfunction-prototypes

"Faking" a JavaScript Constructor


Context

I am working on improving my JavaScript skills and I'm learning more about prototyping. I want to better understand the code in this question and any limitations or problems with it.

One thing that hasn't been obvious is defining more complex constructors that do more than simple initialization. What I want to do is have a Class that calls a web service when it's created without needing to call a method right after initialization.

What I did was create a property and assign a self calling anonymous method to it. It seems to work like I want it to, but I don't know if there is a better approach.

The Code

function AsyncOrderLine(productID) {

    var context = this;

    this.autoValue;
    this._productID = productID;
    this._asyncRequestComplete = false;


    this.hello = function () {
        alert("hello world");
    }

    this.constructor = (function () {
        context.hello();
        context.autoValue = "testing: " + productID + "(" +        context._asyncRequestComplete + ")";
    })()

}

The Result

 var _asyncOrderLine = new AsyncOrderLine(1001);

Alert Shown: "Hello World"

 _asyncOrderLine.autoValue = testing: 1001(false)
 _asyncOrderLine.constructor = 'undefined'

In this case I want the constructor to remain undefined once the object is created.

Question

Is there a better way of doing this? Could there be any unforeseen side affects using this approach?


Solution

  • There's no need to complicate things like that. You can run whatever code you want inside your constructor:

    function AsyncOrderLine(productID) {
    
        this.autoValue;
        this._productID = productID;
        this._asyncRequestComplete = false;
    
        this.hello = function () {
            alert("hello world");
        }
    
        // Run whatever arbitrary code you want...    
        this.hello();
        this.autoValue = "testing: " + productID + "(" + context._asyncRequestComplete + ")";
    }