使用构造函数函数的Javascript继承

Javascript Inheritance using constructor functions

本文关键字:Javascript 继承 函数 构造函数      更新时间:2023-09-26

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

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。

其他方式

function Fruit() {
    this.isEatable = function() {
        return this.eatable;
    };
}
function Apple(eatable , sweet) {
    this.sweet=sweet;
    this.eatable=eatable;
    this.isSweet = function() {
        return this.sweet;
    };
    this.prototype= Fruit.apply(this);
}
var a = new Apple(true, false);
console.log(a.isEatable()); 

这和@Asryael有点像,我想

简短的解释:prototype将新的Fruit对象与Apple的this绑定,因此您不需要在根对象中再次传递参数,this会处理它。