一般的情况下,假如你创建一个js类的实例,需要这样调用构造函数,比如
(function(){
TestClass=function (param1,param2){
this.result='start';
this.attr1=param1;
this.attr2=param2;
}
TestClass.fn=TestClass.prototype={
add:function(){
this.result=parseInt(this.attr1)+parseInt(this.attr2);
alert(this.result);
},
equals:function(){
if(this.attr1==this.attr2){
this.result=true;
}else{
this.result=false;
}
alert(this.result);
}
}
})()
var test=new TestClass(1,2);
test.add();
test.equals();
//TestClass(1,2).add();
此时你不能像jquery一样用jQuery("x").add()或者$("").add(),那么这个是怎么办到的呢很简单,改版如下:
(function(){
TestClass=function (param1,param2){
return new TestClass.fn.init(param1,param2);
}
TestClass.fn=TestClass.prototype={
add:function(){
this.result=parseInt(this.attr1)+parseInt(this.attr2);
alert(this.result);
},
equals:function(){
if(this.attr1==this.attr2){
this.result=true;
}else{
this.result=false;
}
alert(this.result);
},
init:function(param1,param2){
this.result='start';
this.attr1=param1;
this.attr2=param2;
return this;
}
}
TestClass.fn.init.prototype=TestClass.fn;
})()
TestClass(1,5).equals();
改动很简单:
- 1,构造函数变成return new TestClass.fn.init(param1,param2);
- 2,在TestClass.fn里面加init方法,完成初始化
- 3,加上TestClass.fn.init.prototype=TestClass.fn;这句话,表示让init方法的prototype指向TestClass的prototype,这样构造函数返回的对象就具有了TestClass.prototype里面定义的方法。
此时,你就可以直接 TestClass(1,5).equals();这样调用了,当然了,把TestClass换成$也是可行的,只要加上这句
var $=TestClass;
window.$=$;
window.TestClass=TestClass;
下篇讲解稍微进阶一点的知识。
分享到:
相关推荐
jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码jQuery源码...
NULL 博文链接:https://duyunfei.iteye.com/blog/857841
Jquery源码分析 清晰 Jquery源码分析 清晰 Jquery源码分析 清晰 Jquery源码分析 清晰
jquery1.2.6源码分析,其中里面含有源码详细的中文注释
锋利的jQuery 源码锋利的jQuery 源码锋利的jQuery 源码锋利的jQuery 源码锋利的jQuery 源码锋利的jQuery 源码
jquery源码分析,包括入口技术,选择器入口,以及在选择器使用的时候需要注意的优化思路
jQuery源码分析视频教程总计116课,按照jquery每个区段实现的内容,精确地讲解源码中是怎么实现我们开发中用到的jquery得方法的
jQuery源码分析系列.pdf
jquery最新源码jquery最新源码jquery最新源码
jQuery源码解读,jQuery源码解读
jquery源码 带格式 读了一遍挺不错了 在这分享了
Head First jQuery 中文版 源码
jQuery源码分析-插件
jQuery学习资料 锋利的Jquery 源码 锋利的Jquery 源码 锋利的Jquery 源码
最新的开发版jQuery源码。jquery-1.8.0.js
Jquery1.26版本的源码分析,pdf格式文档,相当清淅的书籍,前端开发者必看的类库书籍,...采用CSS方式查找Dim节点,jQuery类数组的分析,Dom元素的属性及操作,Event事件分析及应用,jquery中的Ajax实现及源码分析等内容.
jquery框架源码,web前端开发框架
jquery 源码分析