Typescript和__proto__属性

Fro*_*tie 4 prototype chain typescript

因此,每次提及__proto__时,通常都会提到Brendan Eich不要使用它的请求.我一直在使用Typescript中的一些反射,将类的原型链导航到使用它的提供的祖先类,并且希望注入一个包含类元数据的原型属性.

有没有人对我可能产生的性能开销有任何细节,或者有一个不依赖__proto__的解决方案?

编辑 - 更新代码.这只是我输入的一个人为的例子,但它说明了我希望做的事情.我不太确定如何对由__proto__变异引起的经历的减速进行基准测试.但无论如何,我试了一下.实例化,原型属性访问和方法调用在修改时执行没有区别.

class Base {
    public getClassName() : string {
        return this['_className'] || undefined;
    }
}

class Intermediate extends Base {   
}

class Final extends Intermediate {  
}

function traverseProtoChain(derivedClass, baseClass) {
    var cursor = derivedClass.prototype;
    while (cursor instanceof baseClass) {
        if (isDefined(cursor.constructor)) {
            var className = getProtoName(cursor);
            if (isValidString(className)) 
                cursor['_className'] = getProtoName(cursor);
        }           

        if (isDefined(cursor.__proto__)) {
            cursor = cursor.__proto__;
        }   
    }   
}
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 8

您可以使用ECMAScript 5.1标准:

Object.getPrototypeOf(cursor)
Run Code Online (Sandbox Code Playgroud)

对于非常旧版本的浏览器,__proto__如果Object.getPrototypeOf不存在,您可以尝试回退,但是根据您的特定上下文,您可以决定这些浏览器是否重要.

这是一个显示这个的例子.bar.prototype不起作用,因为它是一个实例.getPrototypeOf工作,并给你与沮丧相同的答案__proto__.

class Foo {
    constructor(name: string) {

    }
}

class Bar extends Foo {

}

var bar = new Bar('x');

console.log(bar.prototype);
console.log(Object.getPrototypeOf(bar));
console.log(bar.__proto__);
Run Code Online (Sandbox Code Playgroud)

所以你可以写"让所有人都高兴"......

if (Object.getPrototypeOf) {
    console.log(Object.getPrototypeOf(bar));
} else if (bar.__proto__) {
    console.log(bar.__proto__);
}
Run Code Online (Sandbox Code Playgroud)

最终的曲线球...... __proto__很可能在ECMAScript 6中变得标准化......值得记住!