標籤:
寫了很久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的思考