简体   繁体   中英

Can javascript pass itself from inside the constructor

How can i go from this:

var abc = (function(){ 
  ..  
})();

register(abc); // outside the protected class

to this: (whithout calling register outside the class):

function register(object){ stores the object }

var abc = (function(){
     ..       

     register(this); // inside the protected class
})();

Some background.

A master-class has an object-array of plugins the 'register' function places the plugin. abc would be such a plugin. the plugins following the module patern closures. I would like to place the plugin instances into the list and the plugin be as selfcontained as possible. Additional functions outside the plugin i would like to remove.

I considered: MasterClass.plugins.abc = (function..) but i think this creates a dependency on MasterClass.plugins to be instantiated before any plugins are loaded.

You can use Function.prototype.bind() (to modify the this value) and a var inside, like this:

(function(){
var fun = function(){ alert( this.toString() )}
fun.bind(fun)();
})()

In your case:

(function(){
var fun = function(){ alert( this.toString() )}
register(fun);
})()

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