2013-12-12 87 views
1

我有下面的代码,允许我用插件扩展基本的Lib类。该插件有它自己的上下文和库上下文是以流允许插入参数

Lib = function (test,width) { 
    this.libraryProp = test; 
    this.width = width; 
} 

Lib.extend = function(name,plugin) { 
    this.prototype[name] = function() { 
    return new plugin(this); 
} 
} 

//The plugin 
var myObj = function(lib) { 
    this.chart = chart; 
    this.pluginProp = 'plug'; 
    console.log('this library prop = ' + this.chart.libraryProp); 
} 

//A plugin method 
myObj.prototype.ggg = function() { 
    console.log('plugin prop in plugin prototype ' + this.pluginProp); 
    console.log(this.chart); 
    console.log('______________________________________________'); 
} 

//extend the base library 
Lib.extend('myObj',myObj) 


var p = new Lib('instance 1', 900); 
var u = p.myObj(); 
u.ggg(); 


var m = new Lib('instance 2',800); 
var k = m.myObj(); 
k.ggg(); 

工作小提琴:http://jsfiddle.net/pnwLv/2/

它所有的作品,但我目前无法养活任何插件,像参数,以便:

var u = p.myObj('param1','param2'); 

我该如何重新考虑扩展方法来允许这个?

回答

1

像这样的东西?

Lib.extend = function (name, plugin) { 
    this.prototype[name] = function() { 
    var args = Array.prototype.slice.call(arguments), 
     obj = Object.create(plugin.prototype); // Create a new object from the plugin prototype 

    args.unshift(this); // Add Lib instance as the first argument 
    plugin.apply(obj, args); // Call the plugin constructor with the new object as the context 
    return obj; // Return the newly created object 
    } 
} 

然后你可以检索插件构造这些参数:

var myObj = function(lib, param1, param2) { 
    this.lib = lib; 
    this.pluginProp = 'plug'; 
    console.log('this library prop = ' + this.lib.libraryProp); 
} 
+0

这基本上是我所需要的。我只是将Object.create替换为polyfill,因为我需要Ie8支持。谢谢! –