jQuery定义类及扩展

这个自定义类还是有点困惑滴。先看网上有个人做滴,模仿jQuery定义一个jQuery对象。

<script type="text/javascript">
// zchain-0.1.js
function $(selector){//定义了名为jQuery的对象  用滴是构造法
	return new $.prototype.init(selector);//有点怪 为什么会有return呢?
}
$.prototype={
	init:function(selector){
		if(selector === undefined){
			this.length = 0;
			return this;
		}
		if(selector.nodeType==1){//怀疑这句有问题
		    alert("div");
			this[0] = selector;
		}else{
		    alert("test");
			this[0]=document.getElementById(selector);
		}
		this.length=1;
	},
	css:function(name,value){
		this[0].style[name] = value;
		return this;//链式调用
	},
	hide:function(){
		var self=this;
		setTimeout(function(){
			self[0].style.display="none";
		},3000);
		return this;//链式调用
	}
}
$.prototype.init.prototype=$.prototype;
//var obj = $();   
//console.dir(obj); 
</script>
<div id='content'>3 seconds later I will hide.</div>

</body>
</html>
<script type="text/javascript">
	//alert(document.getElementsByTagName('div'));
	$('content').css("color","red").hide();
</script>

刚开始看这段代码时晕晕滴,先定义一个类吧:function $(..)名字为$,让我看得很疑惑,原来它是定义一个jQuery的类呀。然后在后面调用的时候又发现一个问题:$('content'),这个content命名是一个#id类型嘛,然后他在构造函数中既然有:selector.nodeType==1。(感觉那个网友有错)。

接下来总结下类滴扩展吧:方法一、通过jQuery.extend扩展 

还是先看下个例子(摘录别人滴,但自己有测试了下):

<script type="text/javascript">
function fun(){}//定义一个类(函数)

//为该类(函数)添加一个静态方法extend
fun.extend=function(obj){
	for(var a in obj)
		this[a] = obj[a];//注意:这里的tihs即fun
}

//调用extend为该类添加了静态属性name,静态方法method1
fun.extend({name:"fun",method1:function(){}});

//输出name,prototype,extend,method1
console.dir(fun);//输出fun的方法(为什么没有包括属性)
console.log("%o",fun);
</script>

上面有注释,entend也是fun的一个静态方法,这不是扩展吗?怎么会是一个方法呢?于是我把entend方法注释掉。运行在firebug就出错,提示:fun.extend is not a function。哦,再看看extend做了什么吧。

传了一个参数,然后吧这些参数赋值给fun类。原来是这样,如果没有先定义extend的话,那接下去就无法对其进行扩展了。至少我现在还没有发现其他方法。

扩展方法2:通过jQuery.fn.extend扩展 

这个方法跟通过jQuery.extend扩展方法基本一样,感觉没差别。只要吧通过jQuery.fn.extend 替换下通过jQuery.extend就行啦。

原文地址:https://www.cnblogs.com/huaizuo/p/2122068.html