前言
虽然 javascript 没有明确的类的概念,但是用类来理解它,会更方便。
例如利用构造函数,可以new出实例对象。如
<script>
function Person(){
this.name=name;
this.say=function(){
console.log('i am '+this.name)
}
}
Person.prototype.run=function(){ console.log('hhhh')}//原型对象
var zhangsan=new Person()//zhangsan指向 Person.prototype
</script>
jQuery便是一个封装得非常好的类,比如我们用 语句 $("#btn1") 会生成一个 jQuery类的实例。
1. jQuery.extend(object);
(1)为jQuery类添加类方法,可以理解为添加静态方法,就类似于Person中的this.name this.say this.xx等等。
(2)Person的这些this属性方法调用就是Person.name,Person.say。
综上可理解:为jQuery类添加类方法就是jQuery.属性名或jQuery.方名。
例子:
<script>
$.extend({
add:function(a,b){
return a+b;
}
})
$.add(5,8) //return 13
</script>
2. Query.fn.extend(object)
(1)对jQuery.prototype进得扩展,fn等于prototype。
Query.fn.extend(object)就类似于Person.prototype.xx=xx.
例子
$.fn.extend({
clickwhile:function(){
$(this).click(function(){
alert($(this).val())
})
}
})
$('input').clickwhile();//当点击输入框会弹出该对象的Value值
$(‘input’)生成一个 jQuery类的实例。该实例对象指向Jquery.prototype.
类似于zhangsan指向 Person.prototype
参考:https://blog.youkuaiyun.com/baple/article/details/11684621
http://blog.sina.com.cn/s/blog_ba548bf90101hu25.html##1