原型与传递对象的性能 属性

performance of prototype vs passing object property

我有一个 class 需要从其父级引用 属性。我想知道将 属性 传递给子 class 的构造函数并将其设置为子 class 的新 属性 是否更好,或者而在父 class 中将其添加为子 class.

的原型

实施A:

// parent-class.js

let childClass = require('childClass.js');

class foo {

    constructor() {
        this.initChild = new childClass(this.superCoolMethod);
    }

    superCoolMethod() {
         return 'this method does super cool stuff and the child needs it';
    }

}

// child-class.js

class bar {
    constructor(superCoolMethod) {
        this.superCoolMethod = superCoolMethod;
    }

    callCoolMethod() {
        this.superCoolMethod();
    }

}

实施 B:

// parent-class.js

let childClass = require('childClass.js');

class foo {
    constructor() {
        this.childClass.prototype.superCoolMethod = superCoolMethod;
        this.initChild = new childClass(this.superCoolMethod);
    }

    superCoolMethod() {
         return 'this method does super cool stuff and the child needs it';
    }
}

// child-class.js

class bar {

    callCoolMethod() {
        this.superCoolMethod();
    }

}

哪种实现的性能更高,是否有更好的方法来实现这一点?

Which implementation would be more performant...

没关系。 class foo 伸出手来改变 class childClass 的原型是一个非常糟糕的主意。 (但是实例 属性 会 very-very-very-slightly 更快,因为 属性 查找在实例处停止,而不是在实例中找不到它然后需要查看原型。在现实世界中,它产生任何明显差异的几率几乎为零。)

记住:所有其他 childClass 实例都使用该原型,即使是那些与 foo 代码完全无关的实例。实例和它的原型之间的link是一个link;实例不会获得其原型的 copy。例如:

class Example {
};

const e = new Example();

console.log(e.foo);   // undefined

Example.prototype.foo = 42;

console.log(e.foo);   // 42

and are there any better ways to achieve this?

在实例上将其设置为 属性(例如,实施 A 或类似实施)。

我会把它设置为 属性。这是有意义的方式。如果更改原型,您将在所有后续 new childClass() 对象中拥有添加的方法。这可能不是我们想要的行为。