Javascript插件公共方法不起作用
决定在vanilla JS中重建jQuery插件时遇到了一个问题,我似乎无法让plublic方法正常工作。所有其他逻辑都有效,但公共方法无效。我以update方法为例Javascript插件公共方法不起作用,javascript,Javascript,决定在vanilla JS中重建jQuery插件时遇到了一个问题,我似乎无法让plublic方法正常工作。所有其他逻辑都有效,但公共方法无效。我以update方法为例 (function(root, factory) { if (typeof define === 'function' && define.amd) { define([], factory(root)); } else if (typeof exports === 'object'
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory(root));
} else if (typeof exports === 'object') {
module.exports = factory(root);
} else {
root.Plug = factory(root);
}
})(typeof global !== "undefined" ? global : this.window || this.global, function(root) {
var _settings;
var defaults = {
// default values
}
function runPlugin(){
alert('it works')
}
var Plug = function(options) {
var Plug = {};
var settings;
_settings = extend(settings || defSettings, options || {});
var init = (function() {
//init logic
runPlugin();
...
}());
Plug.update = function(msg){
alert(msg)
}
}
return Plug;
});
var plug = new Plug({//settings...}); //works
var plug = new Plug().update('test'); //does not work
在
Plug
功能中,您应该参考this
而不是Plug
来添加方法。所以
this.update = ...
不是
(注意,为了让您的示例运行,我不得不做一些小动作)
(函数(根,工厂){
if(typeof define=='function'&&define.amd){
定义([],工厂(根));
}else if(导出的类型==='object'){
module.exports=工厂(根);
}否则{
根。插头=工厂(根);
}
})(typeof global!=“未定义”?全局:this.window | | this.global,函数(根){
变量设置;
var默认值={
//默认值
}
函数runPlugin(){
警报(“它工作正常”)
}
var插头=功能(选项){
var设置;
_设置=Object.assign(设置| |默认值,选项|{});
var init=(函数(){
//初始化逻辑
runPlugin();
}());
this.update=函数(msg){
警报(msg)
}
}
回油塞;
});
var plug=新的plug({})//作品
var plug=new plug().update('test')代码>
Plug.update = ....