jquery扩展例子

<div id='div'>div test</div>



window.οnlοad=function(){
	alert(3);
}
$(function(){
	alert(2);
    var option ={
    	name:'div'
    };
	$("#div").hello(option);//绑定div  点击后弹出div文本信息
});
;(function($){
	alert(1);
	
	var thisObjTest = function(){
		alert(this);//this是window对象
	};
	thisObjTest();
	
	//声明对象Hello
	var Hello = function(option){	
		this.init(option);//this是Hello对象,所以查找Hello的init方法
	};
	Hello.prototype.init = function(){
		alert('hello init');//被覆盖
	};
	//扩展Hello对象
	$.extend(Hello,{
		prototype:{
		init:function(option){
		    var me = this;//this是Hello对象
		    me.option = $.extend({},option);
		    me.targetObj = option._target_obj;
		    $(me.targetObj).click(function(){
		    	me.printd(this);//this是targetObj对象
		    });
			alert('extend init');
		},
		printd:function(obj){
			alert("opt name="+this.option.name+" "+$(obj).text());
		}
		}
	});
	//扩展到实例对象方法中
	$.fn.extend({
		hello:function (option){
			      $.extend(option,{_target_obj:this}); 
	  		      var h = new Hello(option);//生成一Hello对象
			  }
	});
 
})(jQuery);

 


页面加载结果:

        1                               //;(function($){})(jQuery)首先执行          alert(1);   

        [object Window]    //alert(this);

        2                              //$(function(){});    dom元素加载完后执行  alert(2)

      extend init                //Hello对象的init方法     alert('extend init');

       3                               //页面内容所以加载完成   window.onload执行   alert(3)  


点击页面div  结果

       opt name=div  my name is div      //    alert("opt name="+this.option.name+" "+$(obj).text());


1.首先对比(function($){})(jQuery)、$(function(){})、window.onload的执行顺序,结果是(function($){})(jQuery) > $(function(){}) > window.onload

2.对比了函数中的this对象,this对象是指调用改函数的对象,所以thisObjTest();默认是由window调用,所以thisObjTest();函数中的this是指window对象

3.使用jquery的extend函数对Hello对象进行扩展

extend(dest,src1,src2,src3...);把src1-src3合并到dest后返回dest,改变了dest的结构,所以Hello的init被覆盖。这里还有一个
extend(boolean,dest,src1,src2,src3...)第一个参数指是否进行深度合并,可以参看这里jQuery.extend 函数详解
4.使用fn.extend()函数进行jquery实例对象的函数扩展,可以理解为jquery实例对象可以调用
5.最后对页面div元素进行测试  $("#div").hello(option);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值