(function () {
//1.暴露外部的一个接口
var gquery = window.gquery = window.$$ = function (selector) {
return new gquery.pt.init(selector);
};
//2.处理原型对象,以利于扩展
gquery.pt = gquery.prototype = {
init: function (selector) {
var elements = document.getElementsByTagName(selector);
Array.prototype.push.apply(this, elements)
return this;
},
gquery: "v1.0.0",
length: 0,
size: function () {
console.log(this.length);
}
};
gquery.pt.init.prototype = gquery.prototype;
//3.实现继承,并且只处理只有一个参数,也就是插件的扩展
gquery.extend = gquery.pt.extend = function () {
var o = arguments[0];
for (var p in o) {
this[p] = o[p]
}
};
//4.添加静态方法
gquery.extend({
hello: function () {
console.log("这是静态方法");
},
//4.1累加的方法
add: function (arguemnts) {
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
},
//4.2去除数组重复的方法
delRepeat: function (arr) {
return [...new Set(arr)]
},
//4.3添加outline
addOutLine: function () {
[].forEach.call($$("*"), function (a) {
a.style.outline = "1px solid #" + (~~(Math.random() * (1 << 24))).toString(16)
})
},
//4.4交换两个数
exchangeValue: function (a, b) {
a ^= b;
b ^= a;
a ^= b;
return [a, b]
},
//4.5取数组中的最大值
maxArrValue: function (arr) {
return Math.max.apply(Math, arr)
},
//4.6取数组中的最小值
minArrValue: function (arr) {
return Math.min.apply(Math, arr)
},
//4.7给予星评分
getStars: function (rate) {
return ("★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate));
}
});
//5.添加实例方法
gquery.pt.extend({
hello: function () {
console.log("这是实例的方法");
}
});
})()
仿jQuery式的插件形式
最新推荐文章于 2022-04-26 20:01:39 发布