Javascript 允许向插件输入参数

Javascript 允许向插件输入参数,javascript,Javascript,我有下面的代码,它允许我用一个插件扩展基库类。插件有自己的上下文,库上下文被输入 Lib = function (test,width) { this.libraryProp = test; this.width = width; } Lib.extend = function(name,plugin) { this.prototype[name] = function() { return new plugin(this); } } //The pl

我有下面的代码,它允许我用一个插件扩展基库类。插件有自己的上下文,库上下文被输入

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();
工作小提琴:

这一切都可以工作,但我目前无法提供任何插件参数,如:

var u = p.myObj('param1','param2');
我如何重新考虑extend方法以允许这样做?

类似的内容

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);
}
像这样的

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);
}

这基本上就是我需要的。我只是想用Object.create out替换polyfill,因为我需要Ie8支持。谢谢这基本上就是我需要的。我只是想用Object.create out替换polyfill,因为我需要Ie8支持。谢谢