gpt4 book ai didi

javascript - 原型(prototype)继承中的元对象在上面的 ES5 中有意义吗?

转载 作者:行者123 更新时间:2023-12-03 04:17:14 26 4
gpt4 key购买 nike

我在这里看到两种类型的原型(prototype)继承函数创建模式。

Function.prototype.inherit = function( base ) {
function Meta() {};
Meta.prototype = base;
this.prototype = new Meta();
}

Function.prototype.inherit = function( base ) {
this.prototype = new base();
}

以前的实现似乎没有做任何额外的事情!中间有一个 Meta 函数,它的用例是什么?

最佳答案

Meta 函数的要点是避免调用构造函数可能发生的副作用:

function Base() {
console.log("This should not be called when inheriting!");
}

// If you use `new Base()` as a prototype, an unwanted message is logged

在 ES5 中,它内置为 Object.create :

this.prototype = Object.create(base.prototype);

在 ES6 中,你可以直接使用 a class :

class Derived extends Base {
// ...
}

关于javascript - 原型(prototype)继承中的元对象在上面的 ES5 中有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com