當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript中的静态成员
生活随笔
收集整理的這篇文章主要介紹了
JavaScript中的静态成员
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
靜態:共享
一、公有靜態成員(作為函數的屬性即可):
1 var Gadget = function(price) { 2 this.price = price; 3 } 4 Gadget.isShiny = function(){ 5 var msg = 'you bet';//公有靜態 6 if(this instanceof Gadget){//實例調用時 7 msg += ', it costs ' + this.price + '!'; 8 } 9 return msg; 10 } 11 Gadget.prototype.isShiny = function(){ 12 return Gadget.isShiny.call(this) 13 } 14 15 console.log(Gadget.isShiny());//you bet 此為靜態調用 16 var a = new Gadget(23); 17 console.log(a.isShiny());//you bet, it costs 23! 此為實例調用二、私有靜態成員:
私有:構造函數外部不可訪問
靜態:所有實例共享
通過即時函數創建作用域存放
1 var Person; 2 (function(){ 3 var id = 0;//私有 4 Person = function(){ 5 id ++; 6 this.id = id; 7 } 8 Person.prototype.getId = function(){ 9 console.log(this.id); 10 } 11 Person.prototype.getLastId = function(){ 12 console.log(id); 13 } 14 15 })(); 16 17 18 var p1 = new Person(); 19 p1.getLastId();//1 20 p1.getId();//1 21 22 var p2 = new Person(); 23 p2.getLastId();//2 24 p2.getId()//2 25 26 var p3 = new Person(); 27 p3.getLastId();//3 28 p3.getId();//3 29 30 31 p1.getId();//1 32 p2.getId();//2 33 p3.getId();//3?
?
注:JavaScript設計 P108-111 略變
轉載于:https://www.cnblogs.com/redking-fighting/p/6250408.html
總結
以上是生活随笔為你收集整理的JavaScript中的静态成员的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker - command in
- 下一篇: BZOJ 1711: [Usaco200