简体   繁体   English

使用构造函数的Java继承

[英]Javascript Inheritance using constructor functions

I'm trying to make one constructor function parent of another constructor function. 我试图使一个构造函数成为另一个构造函数的父代。

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

But as you can see I get an error , what is the reason ? 但是如您所见,我得到一个错误,原因是什么? What is the better way to make one function inherit from another function ? 使一个函数从另一函数继承的更好方法是什么?

I also tried the following , and I still get the same error : 我也尝试了以下方法,但仍然出现相同的错误:

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

Try the following 尝试以下

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());

This is based off the (Very useful) code given as an example in the MDN Object.create documentation. 这基于MDN Object.create文档中作为示例给出的(非常有用)代码。 Here's a JSFiddle . 这是一个JSFiddle

just other way 换一种方式

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()); 

It's somewhat same thing as @Asryael i guess 我猜这和@Asryael有点一样

short explanation: prototype binds new Fruit object with this of Apple , so you don't need to pass parameters again in root object, this takes care of it . 简短说明:原型将新的Fruit对象与this Apple绑定在一起,因此您无需在根对象中再次传递参数, this就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM