简体   繁体   中英

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,

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM