给jQuery添加静态方法
function jQuery() {};
jQuery.extend = function (obj) {
for (const [key, value] of Object.entries(obj)) {
this[key] = value;
}
}
jQuery.extend({
sum: function (a, b) {
return a + b
},
reduce: function (a, b) {
return a - b
}
})
console.log(jQuery.sum(1, 1));
console.log(jQuery.reduce(1, 1));
给jQuery添加实例方法
function jQuery() {};
jQuery.prototype.extend = function (obj) {
console.log(this);
for (const [key, value] of Object.entries(obj)) {
this[key] = value;
}
}
let newJquery = new jQuery();
newJquery.extend({
sum: function (a, b) {
return a + b
},
reduce: function (a, b) {
return a - b
},
isDemo: function () {
console.log('23');
}
})
console.log(newJquery.sum(5, 6));
console.log(newJquery.reduce(7, 8));
newJquery.isDemo();
综合
function jQuery() {};
jQuery.extend = jQuery.prototype.extend = function (obj) {
for (const [key, value] of Object.entries(obj)) {
this[key] = value;
}
}
jQuery.extend({
sum: function (a, b) {
return a + b
},
reduce: function (a, b) {
return a - b
},
})
let newJquery = new jQuery();
newJquery.extend({
sum: function (a, b) {
return a + b
},
reduce: function (a, b) {
return a - b
},
isDemo: function () {
return 'isdemo'
}
})
console.log(jQuery.sum(1, 2));
console.log(newJquery.sum(5, 5));
console.log(newJquery.isDemo());