生活随笔
收集整理的這篇文章主要介紹了
用JAVASCRIPT实现静态对象、静态方法和静态属性
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Javascript語言的面向對象特征很弱,其他面向對象語言在創(chuàng)建類時只要使用關鍵字static即可指定類為靜態(tài)類,Javascript沒有提供static這樣的關鍵字,要讓Javascript也具有“靜態(tài)”特性只有靠一些“奇技淫巧”了。
代碼中列舉了兩種靜態(tài)方法/屬性的實現方式,一種是靜態(tài)類的靜態(tài)方法和屬性,另一種是非靜態(tài)類的靜態(tài)方法和屬性,代碼說明都寫在每行的代碼注釋里,這里就不重復了。
?
| 1 | /**************************************** |
?
?
?
?
| 1 | *****************************************/ |
?
?
?
?
?
| 1 | alert(‘Today is ‘ + this.today); |
?
?
?
?
| 1 | //靜態(tài)對象可直接使用,無需創(chuàng)建實例 |
?
| 1 | alert(‘It is ‘ + Time.weather + ‘ today.’); |
?
?
?
| 1 | //下面的代碼會出錯,因為靜態(tài)類不能創(chuàng)建實例 |
?
?
?
?
| 1 | /**************************************** |
?
?
| 1 | * 普通對象,同時擁有靜態(tài)和非靜態(tài)屬性、方法 |
?
?
?
| 1 | *?? 1.靜態(tài)方法/屬性使用類名訪問 |
?
| 1 | *?? 2.非靜態(tài)方法/屬性使用實例名訪問 |
?
| 1 | *****************************************/ |
?
| 1 | function Person(name) { |
?
?
?
?
| 1 | this.show = function() { |
?
| 1 | alert(‘My name is ‘ + this.name + ‘.’); |
?
?
?
?
?
?
| 1 | Person.cry = function() { |
?
?
?
| 1 | //使用prototype關鍵字添加非靜態(tài)屬性,每個人的牙可能不一樣多 |
?
| 1 | Person.prototype.teeth = 32; |
?
?
| 1 | //非靜態(tài)方法必須通過類的實例來訪問 |
?
| 1 | var me = new Person(‘Zhangsan’); |
?
?
?
| 1 | alert(‘I have ‘ + me.teeth + ‘ teeth.’); |
?
?
?
| 1 | alert(‘I have ‘ + Person.mouth + ‘ mouth.’); |
?
?
| 1 2 3 | var p=new Person("x"); ????alert(p.mouth);//回顯示未定義 ????p.cry();//會顯示Uncaught TypeError: Object #<person> has no method 'cry'</person> |
?
| 1 | 可以發(fā)現,實例對象沒法訪問類的靜態(tài)方法和屬性。需要訪問只能使用類名 |
?
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <pre class="brush:java;"><span style="color:#333333;">function Person(name){ ????????this.name=name; ????????this.show=function(){ ????????????alert("My Name is "+this.name); ????????}; ????}; ????? ????Person.mouth=1; ????Person.cry=function(){ ????????alert("wa wa"); ????} ????Person.prototype.teeth=32; ????? ????? ????var p=new Person("x"); ????alert(Person["mouth"]);//1 ????p["show"]();//My name is x</span></pre><br><br> |
?
?
| 1 | 在Jquery中可以這樣使用對象的靜態(tài)方法和屬性: |
?
| 1 2 3 | <pre class="brush:java;">var arr=new Array(); ???arr["push"]("x"); ???alert(arr["length"]);//1</pre>歡迎大家補充討論,共同進步! |
?
?
?
?
總結
以上是生活随笔為你收集整理的用JAVASCRIPT实现静态对象、静态方法和静态属性的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。