将ES6插件扩展为jQuery原型
我想请一些帮助,因为我无法使用模块和类转换ES6中的经典jQuery(v2)插件。
在ECMAScript 5中,我们可以将jQuery插件附加到jQuery原型中,如下所示:
app.js – 通过HTML 标签加载jQuery
$.fn.myPlugin = function() {}; $('div').myPlugin();
它工作:)。 在ES6中,我会写这样的东西:
myPlugin.es6:
import $ from 'jquery'; export default class myPlugin extends $ { // Could i use constructor() method ??? }
app.es6:
import $ from 'jquery'; import myPlugin from 'myPlugin.es6'; $('div').myPlugin();
最后,它不起作用……
我搜索过,之前没有人问过这个问题。
我使用Babel将ES6转换为ES5。
$.fn
只是一个对象。 在$
的原型中添加新属性没有任何魔力。 因此,代码$.fn.myPlugin = function() {}
等于$.prototype.myPlugin = function() {}
。
$.fn === $.prototype; // true
为了能够以标准方式( $('div').func()
)调用$
对象上的函数,需要将此函数添加到$
object。
你没有在es6代码中添加它。
从而,
import $ from 'jquery'; export default class myPlugin extends $ { // Could i use constructor() method ??? }
手段(差不多)
var myPlugin = function() {}; myPlugin.prototype = Object.create($.prototype); return { default: myPlugin };
我不确定你应该扩展$ .fn,但也许你需要它。
与
import $ from 'jquery'; import myPlugin from 'myPlugin.es6';
它的意思是
var $ = require('jquery'); var myPlugin = require('myPlugin'); // a reference to the 'export.default' object from 'myPlugin.es6'
因此, $.fn
对象和myPlugin
函数之间没有任何关联。
你应该在某处创建连接。 它可以在一个特殊的模块中,比如plugins
,你可以将所有需要的插件注入$.fn
对象:
import $ from 'jquery'; import plugin1 from 'plugin1.es6'; // should contain 'name' import plugin2 from 'plugin2.es6'; ... import plugin10 from 'plugin10.es6'; [plugin1, plugin2, ..., plugin10].forEach(plugin => $.fn[plugin.name] = plugin);
或者你可以在’myPlugin.es6’中为导出的对象添加’initialize’方法,并在第一次使用之前调用它: init($) { $.fn.myPlugin = myPlugin; }
init($) { $.fn.myPlugin = myPlugin; }
等等。
您可以像以往一样在ES6中的jQuery原型上安装新方法。 他们没有任何改变。 你不打算inheritancejQuery,所以使用class
或extends
是没有意义的。
// myPlugin.es6: import $ from 'jquery'; $.fn.myPlugin = function() { … };
// app.es6: import $ from 'jquery'; import 'myPlugin.es6'; $('div').myPlugin();