javascript - Add self executing init method to constructor function? -
let’s have constructor function not have access to. constructor function want inject self executing init method gets executed whenever new instance gets created constructor.
for example: let’s there cat constructor, unfortunatly not have access it:
function cat() { // ...code not have access // ...maybe comes external file or something? }
and can of course create new cats:
var coolcat = new cat();
all , have new cat instance.
but want (if actaully had access cat constructor function body, of course not!) this:
function cat() { this.roaroninit = function() { alert(’roooaaar!’); }; this.roaroninit(); }
…so when this:
var coolcat = new cat();
…i cool roar-alert box!
i understand how add method roaroninit cat constructor (cat.prototype.roaroninit = function …) there way can add call method (which gets executed whenever cat instance created) constructor body?
this seems such trivial thing, , it’s super easy, can’t seem figure out afternoon! bearing me.
update
thanks answers far! did forget 1 important thing, , not know in advance constructor function be, or it's name etc. because i'm running through function accepts constructor parameter, , returns constructor (with it's original name/prototype) back.
let's start definition of cat
:
function cat(name){ this.name=name; } cat.prototype.meow=function(){alert(this.name)}
now, can overwrite new constructor returns regular cat
, after running our script:
var oldcat = cat; function cat(name){ var self=new oldcat(name); self.roaroninit=function(){alert("rooooaaarrr")}; self.roaroninit(); return self; }
we can new cat("muffin")
, , roar, , we'll still have access properties on original cat
prototype chain. show in example snippet:
// safe, define original oldcat() function oldcat(name){ this.name=name; } oldcat.prototype.meow=function(){alert(this.name)} //var oldcat = cat; function cat(name){ var self=new oldcat(name); self.roaroninit=function(){alert("rooooaaarrr")}; self.roaroninit(); return self; } var coolcat = new cat("muffin"); coolcat.meow();
now, if want abstract accept function, it's not hard. have bit of work constructor, pass arguments. javascript - create instance array of arguments
function injecttoconstructor(c){ return function(){ var self = new (c.bind.apply(c,[c].concat([].slice.call(arguments))))(); console.log("object initiated:"); console.log(self); return self; }; }
then can like:
cat = injecttoconstructor(cat); var coolcat = new cat("muffin"); // logs 2 items coolcat.meow();
Comments
Post a Comment