2017-05-29 38 views
0

它很容易從一個JavaScript對象得到反射,就像下面的代碼。有沒有辦法從「類」或功能,而不是從一個對象反映JavaScript屬性和方法?

var getAllMembers = function (obj) { 
    var members = {}; 
    members.properties = []; 
    members.methods = []; 

    for (var prop in obj) { 
     if (typeof obj[prop] != 'function') 
      members.properties.push(prop); 
     else members.methods.push(prop); 
    } 
    return members; 
} 

function demo_class(na, nb) { 
    this.a = na; 
    this.b = nb; 

    this.funca = function() { 
     console.log(this.a); 
    } 
    this.funcb = function() { 
     console.log(this.b); 
    } 
} 

var x = new demo_class(1234, 4321); 

var members = getAllMembers(x); 

console.log(members.properties); // [ 'a', 'b' ] 
console.log(members.methods);  // [ 'funca', 'funcb' ] 

我的問題是:有沒有辦法從類或函數而不是從對象獲取屬性和方法?例如,像這樣:

var members = getAllMembers(demo_class); // Only can get '[] []' 

回答

0

在javascript中有類沒有真正的概念,因爲它是一個原型的語言。函數是一個對象。

你可以做的是測試如果你的對象有一個名爲函數的構造,以測試它是否與函數或不是一個池莉構建對象。如果沒有,你可以創建一個實例像你已經做了獲取屬性:

注:如果您使用的關鍵字功能(通過另一個名爲功能不構成)中定義的類的構造函數,這隻會工作。如果您不使用hasOwnProperty()函數,您的函數也將從原型鏈中獲取所有繼承的屬性。

var getAllMembers = function (obj) { 
    var members = {}, toTest; 
    members.properties = []; 
    members.methods = []; 

    //construct object if argument is a constructor 
    toTest = (obj.constructor === Function) ? new obj() : obj; 

    for (var prop in toTest) { 
     if (typeof toTest[prop] != 'function') 
      members.properties.push(prop); 
     else members.methods.push(prop); 
    } 
    return members; 
} 

function demo_class(na, nb) { 
    this.a = na; 
    this.b = nb; 

    this.funca = function() { 
     console.log(this.a); 
    } 
    this.funcb = function() { 
     console.log(this.b); 
    } 
} 

var x = new demo_class(1234, 4321); 

var members = getAllMembers(x); 

console.log(members.properties); // [ 'a', 'b' ] 
console.log(members.methods);  // [ 'funca', 'funcb' ] 

var members = getAllMembers(demo_class); 
0

在Javascript中,一切都是對象。它不存在類概念。因此,每次使用新運算符(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)時,都會使用該函數作爲構造函數返回一個對象。

您可以使用原型概念得到一個近似這一點。在原型中定義方法的位置而不是構造函數本身。

function Person(name, family) { 
    this.name = name; 
    this.family = family; 
} 

Person.prototype.getFull = function() { 
    return this.name + " " + this.family; 
}; 

這裏有一個文章,解釋它https://www.thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/

相關問題