一段js的思考

來源:互聯網
上載者:User

標籤:

 寫了很久JS,還以為這段代碼可以正常輸出,誰知道輸出超乎我的形象:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="text/javascript">function MSG(a,b,c,d){this.a=a;this.b=b;this.c=c;this.d=d;this.e="喜歡";var that=this;   //方便私人函數haha()訪問this.say=function(){console.log(haha());}this.ca=function(){return that.c+this.e+this.d;}function haha(){return this.a+",今年"+this.b+"歲;";//return this.a+",今年"+this.b+"歲;"+this.ca();//return that.a+",今年"+that.b+"歲;"+that.ca();}}var my=new MSG(‘張三‘,‘25‘,‘男‘,‘美女‘);my.say();</script></head><body></body></html>

  

以下這段代碼居然報錯,嗚嗚嗚嗚嗚。。。。。。。

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="text/javascript">function MSG(a,b,c,d){this.a=a;this.b=b;this.c=c;this.d=d;this.e="喜歡";var that=this;   //方便私人函數haha()訪問this.say=function(){console.log(haha());}this.ca=function(){return that.c+this.e+this.d;}function haha(){//return this.a+",今年"+this.b+"歲;"; return this.a+",今年"+this.b+"歲;"+this.ca();//return that.a+",今年"+that.b+"歲;"+that.ca();}}var my=new MSG(‘張三‘,‘25‘,‘男‘,‘美女‘);my.say();</script></head><body></body></html>

  

修改以上的代碼,讓that=this;此時that和this指向同一位置,就可以啦。。。

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="text/javascript">function MSG(a,b,c,d){this.a=a;this.b=b;this.c=c;this.d=d;this.e="喜歡";var that=this;   //方便私人函數haha()訪問this.say=function(){console.log(haha());}this.ca=function(){return that.c+this.e+this.d;   //this==that}function haha(){//return this.a+",今年"+this.b+"歲;";// return this.a+",今年"+this.b+"歲;"+this.ca();return that.a+",今年"+that.b+"歲;"+that.ca();}}var my=new MSG(‘張三‘,‘25‘,‘男‘,‘美女‘);my.say();</script></head><body></body></html>

  

 

總結:

私人變數】 在對象內部使用‘var‘關鍵字來聲明,而且它只能被私人函數和特權方法訪問。 
【私人方法】 在對象的建構函式裡聲明(或者是通過varfunctionName=function(){...}來定義),
它能被特權方法調用(包括對象的構造方法)和私人方法調用,私人函數只能訪問私人的方法和屬性。 
【特權方法】通過this.methodName=function(){...}來聲明而且可能被對象外部的代碼調用。
它可以使用:this.特權函數() 方式來調用特權函數,使用 :私人函數()方式來調用私人函數。

【公用屬性】 通過this.variableName來定義而且在對象外部是可以讀寫的。不能被私人函數所調用。 
【公用方法】 通過ClassName.prototype.methodName=function(){...}來定義可以從對象外部來調用。 
【原型屬性】 通過ClassName.prototype.propertyName=someValue 來定義。 
【靜態屬性】 通過ClassName.propertyName=someValue 來定義。
【靜態方法】 通過ClassName.funName=function(){...} 來定義。

一段js的思考

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.