$.fn 与$.fn.extend$.
$.fn 和 $.fn.extend 个人理解 主要是在写插件的时候使用,在查找一些文档与学习后
$.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效。
jQuery.fn = jQuery.prototype.
jQuery.fn.extend = jQuery.prototype.extend
然后根据廖雪峰的资料 自己照着写了一下
$.fn.highlight3 = function (options) {
let obj = $.extend({}, $.fn.highlight3.default, options);
let background = obj.background;
let color = obj.color;
this.css("background", background).css("color", color);
console.log(background);
console.log(color);
return this;
}
$.fn.highlight3.default = {
background: "#000000",
color: "#e8e8e8",
}
$("#test-highlight1").highlight3({
background: "#add000",
color: "#fff",
});
$.fn.extend({
areYouConfirm:function(){
return $(this).filter("a").each(function (i) {
var $a = $(this);
var url = $a.attr("href");
if (url&&(url.indexOf("http")=== 0 || url.indexOf("https")===0)) {
$a.attr("href","###")
.append("<i>are you sure</i>")
.click(function () {
if (confirm("确定吗???"+url)) {
window.open(url);
}
});
}
});
},
});
$("#test-external a").areYouConfirm();
可以看出 为了jq的链式调用 所以都写了 return,,, $.fn.extend({xxx:fn}) 与$.fn.xxx = fuction(){}; 都是根据 jquery.prototype 原型实现的
简单阅读了 下 calendar.js 的源码 发现自己对 prototype的使用还是很模糊 自己设计插件时的逻辑也很有问题, calendar.js 中同样涉及了 构造函数,拓展方法,原型等概念, -------------------少年仍需努力..