javaScript插件的写法

时间:2022-04-27 19:09:52

直接上代码,说明看注释

(function($){  
//定义在闭包函数中的全局变量,用来初始化参数,其他的所有函数可以调用
var config;

//一些私有函数,相当于php类中private的私有方法,被主函数调用
var privateFunction = function(){

// 执行代码

console.log(arguments[0]);
}


//主函数包含在method中,对外暴露,可以被jquery的实例对象执行
var methods = {
//初始化的函数,传入参数对象
init: function(options){
// 在每个元素上执行方法,同时返回该jqueryded的实例对象
// console.log(options);
return this.each(function() {
var $this = $(this);
// console.log($this);
// 尝试去获取settings,如果不存在,则返回“undefined”
var settings = $this.data('pluginName');
// console.log(settings);
// 如果获取settings失败,则根据options和default创建它
if(typeof(settings) == 'undefined'){

var defaults = {
name:'zengbing',
sex:'nan',
onSomeEvent: function() {}
};

settings = $.extend({}, defaults, options);
// 保存我们新创建的settings
$this.data('pluginName',settings);
}else{
// 如果我们获取了settings,则将它和options进行合并(这不是必须的,你可以选择不这样做)
settings = $.extend({}, settings, options);

// 如果你想每次都保存options,可以添加下面代码:
$this.data('pluginName', settings);


}

//将该配置参数赋值全局变量,方便其他函数调用
config=settings;

// 执行私有的方法,完成相关逻辑任务
// privateFunction(config.name);

});
},
//销毁缓存的变量
destroy: function(options) {
// 在每个元素中执行代码
return $(this).each(function() {
var $this = $(this);

// 执行代码

// 删除元素对应的数据
$this.removeData('pluginName');
});
},

//其他的主题函数。可以完成对象的其他操作
val: function(options1,options2,options3) {
// 这里的代码通过.eq(0)来获取选择器中的第一个元素的,我们或获取它的HTML内容作为我们的返回值
var someValue = this.eq(0).html();
// 返回值
console.log(arguments);
return someValue;
},

getContent: function(){
return this.each(function(){
var content=$(this).text();
console.log(content);
//获取全局变量的初始化的值
console.log(config.sex)
});
}
};

$.fn.pluginName = function(){
var method = arguments[0];
if(methods[method]) {
method = methods[method];
//将含有length属性的数组获取从第下标为1的之后的数组元素,并返回数组
arguments = Array.prototype.slice.call(arguments,1);
}else if( typeof(method) == 'object' || !method ){
method = methods.init;
}else{
$.error( 'Method ' + method + ' does not exist on jQuery.pluginName' );
return this;
}

//jquery的实例对象将拥有执行method的能力,method的this是指jquery的实例对象
return method.apply(this,arguments);

}

})(jQuery);

//用法实例
var config={
name:'huang',
sex:'nv'
};
//先初始化参数配置,在执行各个主体函数,函数中可以调用config的变量,其实就是jquery的链式操作
$('div.mydiv').pluginName(config).pluginName('getContent').pluginName('val','bing');