javascript - How can I set a default property for an object that's passed into a constructor? -
i'm trying make change in 1 spot affect config object passed instantiations of object. object made available globally follows:
function crayons(){ return { foo: thirdpartyfoo } }
the object initialized in project var myfoo = new crayons().foo({color: "red"});
i'd make {color: "blue"}
default, if doesn't pass in color, blue set.
i tried doing
function crayons(){ var foowithdefaults = function(){ = new thirdpartyfoo(arguments); //this invalid this.color = "blue"; //and overwrite color if set } return { foo: foowithdefaults } }
but new
keyword throwing me off, don't know how create javascript constructor says this = new 3rdpartyfoo
.
what missing?
you can either decorate constructor:
function crayons(){ function foowithdefaults() { 3rdpartyfoo.apply(this, arguments); // you're looking if (!this.color) // or whatever detect "not set" this.color = "blue"; } foowithdefaults.prototype = 3rdpartyfoo.prototype; // make `new` work return { foo: foowithdefaults } }
or make factory returns instance:
function crayons(){ function foowithdefaults(arg) { var = new 3rdpartyfoo(arg); // should know how many arguments takes if (!that.color) // or whatever detect "not set" that.color = "blue"; return that; } return { foo: foowithdefaults } }
here can drop new
when calling var myfoo = crayons.foo({color: "red"});
an alternative modifying instance after creation decorate options passed in, in general better solution:
function crayons(){ function foowithdefaults(arg) { if (!arg.color) // or whatever detect "not set" arg.color = "blue"; return new 3rdpartyfoo(arg); } return { foo: foowithdefaults } }
Comments
Post a Comment