kevinius
kevinius

Reputation: 4620

Javascript Object constructor as a method of another object

I have this object:

var x = function(){

    var returnObj = {

        constructor:function(ieps){

            this.jow = ieps

        }

    }

    returnObj.constructor.prototype.build = function(){

        alert(this.jow)

    }

    return returnObj

}

That i would like to call with this:

var jow = new x.constructor("ieps")
jow.build()

So i try to get the build() to execute the alert but i get a x.build() is undefined.

Any ideas?

thx,

Upvotes: 1

Views: 36

Answers (1)

Nikola Dimitroff
Nikola Dimitroff

Reputation: 6237

x is a function that returns the object, which has a constructor as property. You must first call the function. Secondly, you can't go with new x().constructor("ieps") since that gets parsed as (new x()).constructor("ieps") but you actually need new (x().constructor)("ieps"). Finally, we arrive at:

var jow = new (x().constructor)("ieps")
jow.build()

Upvotes: 1

Related Questions