因此,每次提及__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) 为什么将构造函数从Mammal重置为Cat很重要?我一直在玩这个代码,并没有发现任何"错误"构造函数的负面影响.
function Mammal(name){
this.name=name;
this.offspring=[];
}
Cat.prototype = new Mammal(); // Here's where the inheritance occurs
Cat.prototype.constructor=Cat; // Otherwise instances of Cat would have a constructor of Mammal
function Cat(name){
this.name=name;
}
Run Code Online (Sandbox Code Playgroud)
例如:
function Mammal(name){
this.name=name;
this.offspring=[];
}
Cat.prototype = new Mammal(); // Here's where the inheritance occurs
function Cat(name){
this.name=name;
this.hasFur = true;
}
c1 = new Cat();
alert(c1.hasFur); //returns true;
Run Code Online (Sandbox Code Playgroud) 是否可以在以下示例中获取派生的"类"的名称?我想以某种方式将输出设置为"ChildClass",而不是它的"ParentClass".
function ParentClass() { this.name = 'Bob' }
function ChildClass() { this.name = 'Fred' }
ChildClass.prototype = Object.create(ParentClass.prototype);
var child_instance = new ChildClass()
console.log('ChildClass type:', child_instance.constructor.name)
Run Code Online (Sandbox Code Playgroud)
我意识到我可以this.my_type = 'ChildClass'在ChildClass构造函数中做,但是我有许多扩展ParentClass的类,并且在任何地方都这样做会很不方便.