2013-05-02 115 views
5

我想使用實例訪問靜態屬性。這樣javascript:如何訪問靜態屬性

function User(){ 
    console.log('Constructor: property1=' + this.constructor.property1) ; 
} 
User.prototype = { 
    test: function() { 
     console.log('test: property1=' + this.constructor.property1) ; 
    } 
}  
User.property1 = 10 ; // STATIC PROPERTY 

var inst = new User() ; 
inst.test() ; 

的東西在這裏是在jsfiddle

在我的情況,我不知道該實例屬於哪個類相同的代碼,所以我試圖用實例來訪問靜態屬性的構造函數「屬性,但沒有成功:( 這可能嗎?

+0

不要在javascript中使用word類 – 2013-05-02 18:20:24

+0

@Johan:這個鏈接怎麼和這裏的任何東西相關? – Bergi 2013-05-02 18:28:48

回答

4

所以我試圖用實例來訪問靜態屬性的構造函數」屬性

這就是問題所在,您的實例沒有constructor屬性 - 您已覆蓋整個.prototype對象及其默認屬性。相反,使用

User.prototype.test = function() { 
    console.log('test: property1=' + this.constructor.property1) ; 
}; 

而且你也可能只是通過this.constructor使用User.property1,而不是繞道而行。此外,您無法確保您可能想要調用此方法的所有實例的constructor屬性指向User - 因此可以更直接明確地訪問它。

+0

如何從構造函數外部或靜態方法訪問靜態屬性? – 2013-10-19 19:44:22

+2

@AlanKis:直接在構造函數上,在這裏例如'User.property1'。 – Bergi 2013-10-19 20:28:19

+0

確實,愚蠢的我。 – 2013-10-19 20:31:56

0
function getObjectClass(obj) { 
    if (obj && obj.constructor && obj.constructor.toString) { 
     var arr = obj.constructor.toString().match(
      /function\s*(\w+)/); 

     if (arr && arr.length == 2) { 
      return arr[1]; 
     } 
    } 

    return undefined; 
} 

function User(){ 
    console.log('Constructor: property1=' + this.constructor.property1) ; 
} 

User.property1 = 10 ; 

var inst = new User() ; 

alert(getObjectClass(inst)); 

http://jsfiddle.net/FK9VJ/2/

0

也許你可以看看:http://jsfiddle.net/etm2d/

User.prototype = { 
test: function() { 
    console.log('test: property1=' + this.constructor.property1) ; 
    } 
} 

似乎是有問題的,雖然我還沒有想通了,爲什麼。