kros
kros

Reputation: 13

How to add function to existing one with inheritence

learning javascript at the moment, stuck with inheritance. Question: how can i inherit delay function from first function to second with different text aka -var text

var first = (function () {
    var text = "test!";
    return {
      delay: function(time) {
        setTimeout(function() {
        alert(text);
      }, time)
    }
    }

})();


first.delay(400);
second.delay(1000); 

function second() {
    var text = 'second';
}

Do i need to use first.prototype.delay.call(this, time) ? I can't figure it out. Or Do i need to create delay function like this: first.prototype.delay = function(time) {...} etc... ? How can i achieve this? I guess i can do it in different approaches...

Upvotes: 1

Views: 25

Answers (1)

Bergi
Bergi

Reputation: 665564

You will probably want to have a closer look at closures. Inheritance is not really helping you here, as you need a local closed-over variable for that timeout callback anyway.

Closures are functions produced dynamically by functions - exactly what we need here for dry code.

function makeAlerter(text) {
    return {
        delay: function(time) {
            setTimeout(function() {
                alert(text);
            }, time);
        }
    };
}

var first = makeAlerter("test!");
var second = makeAlerter("second");
var third = …; // as many as you want

first.delay(400);
second.delay(1000);

Upvotes: 1

Related Questions