`
AngelAndAngel
  • 浏览: 231029 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

jquery 源码初探,一步步实现自己的jquery(二)

阅读更多
  一般的情况下,假如你创建一个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; 

下篇讲解稍微进阶一点的知识。




  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics