javascript之定义函数时 this 和prototype区别

注:原文 http://www.2cto.com/kf/201406/307790.html

这里作为学习,写在这里

在面向对象的方式编写js脚本时,定义实例的方法主要有两种:this.XXX = function()P{ 和 function.prototype.XXX= function(){}

function ListCommon2(afirst)
    {
      var first=afirst;
      this.do1=function ()
       {     
         alert("first do"+first);
       }               
       
    }   
     ListCommon2.prototype.do2=function()
    {     
         //  alert("first do"+first);//会出错,不能访问first
           this.do1();  // 通过调用 都do1()方法,间接的来访问 first属性。
    }

  this.do1=function ()和ListCommon2.prototype.do2=function()有什么区别呢?

都相当于类的实例方法,只有new后才能使用,那有什么区别呢?

测试代码:

var t2=new ListCommon2("烧水2");
                t2.do1();//
                t2.do2();//

  经过测试发现:this.do1可以访问构造函数内部的变量first,而ListCommon2.prototype.do2不能访问,但能访问函数this.do1。

如果把ListCommon2.prototype.do2定义在构造函数内部,也就可访问了

function ListCommon2(afirst)
    {
      var first=afirst;
      this.do1=function ()
       {     
         alert("first do"+first);
       }     
       ListCommon2.prototype.do2=function()
       {     
          alert("first do"+first);//定义在内部,就可以访问 first
          // this.do1();
      }        
       //实际上,讲ListCommon2.prototype.do2写在内部,是没有意义的,直接 这样写 this.do2 = ..就可以了,向上面的do1一样。
    //故 function.prototype.do2 = function(){....},一般写在“类”的外部,用来实现向 类 语言(如php)的继承特性,封装特性。do2()方法相当于类内部的方法(类体内的方法,类内部的方法),do1()相当于定义在类体外(子类,对象)的方法。 } //测试代码 var t2=new ListCommon2("烧水2"); t2.do1();// t2.do2();//

  

但作为实例函数,如果定义在构造函数内部,每次实例化都要执行,显然在浪费内存,也不合理。

有些资料上把this.do1这类方法叫做特权方法,主要是为了访问内部的私有字段,这样就可以控制对某些字段的访问。例如如上,就定义了一个私有字段first,只能通过构造函数传递,然后就不能修改了。

ListCommon2.prototype.do2这类方法相当于类的实例方法,但能访问这些特权方法,间接访问私有字段。

 结论:

如果要直接访问私有字段,应该使用特权方法,也就是this定义的方法,应该定义在构造函数内部。相反,如果不需要直接访问私有字段,应该使用prototype定义的方法,而且应该定义在构造函数外部。

原文地址:https://www.cnblogs.com/oxspirt/p/4284331.html