2015-05-28 69 views
1

让我们想象一下,我们有一个JavaScript类:获取一个类的公共属性而不创建它的一个实例?

var Person = (function() { 
    function Person(name, surname) { 
     this.name = name; 
     this.surname = surname; 
    } 
    Person.prototype.saySomething = function (something) { 
     return this.name + " " + this.surname + " says: " + something; 
    }; 
    return Person; 
})(); 

我想重复其方法和属性。我没有问题的方法。

var proto = Person.prototype, 
     methods = Object.keys(proto); 

    // iterate class methods ["saySomething"] 
    for (var i = 0; i < methods.length; i++) { 
    // do something... 
    } 

我的问题是当我想要遍历其属性:

var proto = Person.prototype, 
     targetInstance = new Person(), // this is my problem! 
     properties = Object.getOwnPropertyNames(targetInstance), 

    // iterate class properties ["name", "surname"] 
    for (var i = 0; i < properties.length; i++) { 
    // do something... 
    } 

,我发现的唯一办法就是创建一个实例和使用Object.getOwnPropertyNames。我想使用这段代码作为框架的一部分,所以我不能控制其他开发人员定义的类。我想避免创建一个实例的需要,因为如果构造有某种类似的验证:

function Person(name, surname) { 

    if(typeof name === "undefined" || typeof surname === "undefined"){ 
    throw new Error() 
    } 

    this.name = name; 
    this.surname = surname; 
} 

我将无法使用上面的代码。你知道是否有可能获得一个类的公共属性而不创建它的一个实例?

+1

“据我所知,'不'。”你需要能够询问“Prototype”,而且我不知道你会怎么做。 。 。 –

回答

1

你知道是否有可能获得一个类的公共属性而不创建它的一个实例?

如果你正在谈论运行他们没有,不是没有难看黑客喜欢toString(它给你的函数体的string表示)。

但是,您可以在编译时使用TypeScript语言服务获取这些代码,然后执行代码生成以帮助运行时(https://github.com/Microsoft/TypeScript/wiki/Using-the-Language-Service-API)。

这些都不是微不足道的。

+0

我在想'toString()',但我没有意识到语言服务API谢谢你的答案 –

1

属性在对象构造它们之前不存在。 如果您的类看起来像:

var Person = (function() { 
    Person.prototype.name = null;  
    Person.prototype.surname = null; 
    function Person(name, surname) { 
     this.name = name; 
     this.surname = surname; 
    } 
    Person.prototype.saySomething = function (something) { 
     return this.name + " " + this.surname + " says: " + something; 
    }; 
    return Person; 
})(); 

你会看到姓名太多,但你当然不能看着这样的对象计数。

相关问题