gpt4 book ai didi

带有原型(prototype)的 Javascript 继承

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:25:08 25 4
gpt4 key购买 nike

我用谷歌搜索了 1 小时,但没有找到合适的答案。所以这是我的问题:我如何继承一个类及其原型(prototype)?

我目前有这个解决方案:http://jsfiddle.net/RdxYN/2/

function BaseContent(a, b) {
this.propertyA = 'propertyA';
this.a = a;
this.b = b;
alert('x');
}

BaseContent.prototype.funcA = function () {
alert(this.a + ', ' + this.b);
alert(this.propertyA);
};

function ContentA(a, b) {
BaseContent.call(this, a, b);
this.funcA();
}

ContentA.prototype = new BaseContent;
ContentA.prototype.constructor = ContentA;
ContentA.prototype.parent = BaseContent.prototype;

var Content = new ContentA('c', 'd');

唯一的问题是,BaseContent 被执行了两次。我不想要那个。是否有更好的解决方案或修复方法?

最佳答案

在 JavaScript 中实现继承的新方法是使用 Object.create如下:

function BaseContent(a, b) {
this.propertyA = 'propertyA';
this.a = a;
this.b = b;
alert('x');
}

BaseContent.prototype.funcA = function () {
alert(this.a + ', ' + this.b);
alert(this.propertyA);
};

function ContentA(a, b) {
BaseContent.call(this, a, b);
this.funcA();
}

ContentA.prototype = Object.create(BaseContent.prototype);
ContentA.prototype.constructor = ContentA;
ContentA.prototype.parent = BaseContent.prototype;

var Content = new ContentA('c', 'd');

查看演示:http://jsfiddle.net/RdxYN/7/

您可能应该阅读我关于 Why Prototypal Inheritance Matters 的博文以更深入地了解 JavaScript 中的继承。

关于带有原型(prototype)的 Javascript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033309/

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