gpt4 book ai didi

使用构造函数的 Javascript 继承

转载 作者:行者123 更新时间:2023-11-27 23:44:16 25 4
gpt4 key购买 nike

我正在尝试使一个构造函数成为另一个构造函数的父函数。

function Fruit() {
this.isEatable = function() {
return eatable;
};
}
function Apple(eatable , sweet) {
this.isSweet = function() {
return sweet;
};
var instance = {};
Fruit.apply(instance);
_.extend(this, instance);
}

var a = new Apple(true, false);

console.log(a.isEatable()); // Uncaught ReferenceError: eatable is not defined

但是正如你所看到的,我收到了一个错误,原因是什么?使一个函数继承另一个函数的更好方法是什么?

我也尝试了以下方法,但仍然遇到相同的错误:

function Fruit() {
this.isEatable = function() {
return eatable;
};
}
function Apple(eatable , sweet) {
this.isSweet = function() {
return sweet;
};
}

_.extend(Apple.prototype , Fruit.prototype);// I use lodash library
var a = new Apple(true, false);

console.log(a.isEatable()); // Uncaught ReferenceError: eatable is not defined

最佳答案

尝试以下操作

function Fruit(eatable) {
this.eatable = eatable;
this.isEatable = function() {
return this.eatable;
};
}

function Apple(eatable , sweet) {
// Call the constructor of the inherited 'object'
Fruit.call(this, eatable);

this.sweet = sweet;

this.isSweet = function() {
return this.sweet;
};
}

// Inherit the Fruit.prototype methods for Apple
Apple.prototype = Object.create(Fruit.prototype);

var a = new Apple(true, false);

console.log(a.isEatable());

这是基于 MDN Object.create 中作为示例给出的(非常有用)代码。文档。这是 JSFiddle .

关于使用构造函数的 Javascript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33385134/

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