1

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...

kros
  • 13
  • 2
  • You cannot really "inherit" it - `first.delay` closes over a variable that is inaccessible to you, there's nothing you can do about that but overwrite the function completely. – Bergi Dec 05 '15 at 22:09
  • @Bergi ok, if i just leave `var first = function () { ... }` what then? – kros Dec 05 '15 at 22:10
  • Before thinking about that `text`, please consider that `first` is an object with a property while `second` is a function. Don't mix them. What do you want it to be? – Bergi Dec 05 '15 at 22:10
  • Making `first` into a function doesn't change much (except that it's `first().delay(…)` now) unless you make `text` a *parameter* to that function. Which might as well be the best way to achieve what you want (though it's not "inheritance"). – Bergi Dec 05 '15 at 22:12
  • If we have two functions for example: `first` and `second` how could i append `delay` function to both functions with different alert message? – kros Dec 05 '15 at 22:13
  • Not sure what you mean by "append". Each of the functions *returns an object with a method* - and yes, two different functions could return different objects with differently-acting methods. – Bergi Dec 05 '15 at 22:14
  • I just don't want to create `delay` method for both functions, i want to reuse it. Maybe later i will create `third` method and i want to use it like this `third.delay(666)`. Do i need to use objects then? – kros Dec 05 '15 at 22:18

1 Answers1

1

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);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375