Arian
Arian

Reputation: 7719

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

Upvotes: 1

Views: 79

Answers (2)

JosephGarrone
JosephGarrone

Reputation: 4161

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. Here's a JSFiddle.

Upvotes: 2

Aishwat Singh
Aishwat Singh

Reputation: 4459

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

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 .

Upvotes: -1

Related Questions