-1

I have a printName function as below:

function printName(name) {
  console.log('Name is': , name);
}

Now i want to execute printName.callAfter(3000, 'foo'), which should log

'Name is: foo' after 3 seconds.

I tried writing :

myName.prototype.callAfter = function(time, name) {
  setTimeout(function() {
    printName(name)
  }, time);
}

But its only giving me myName.prototype.callAfter as a defined function but myName.callAfter is undefined.

Please help. Thanks in advance

jass
  • 343
  • 3
  • 15
  • 1
    In your `printName` function, where does `name` come from? Did you mean to accept it as a parameter, or use `this.`, or is it really from the containing context? – T.J. Crowder Sep 18 '17 at 15:57
  • 1
    `myName` isn't defined by your code. You should be getting a reference error. Try providing a [mcve] – Quentin Sep 18 '17 at 15:57
  • @jass: `printName` in your question accepts no parameters. So again: Did you mean it to have `name` in its parameter list? If so, please edit the question to fix that. Live examples also belong **in** the question (via Stack Snippets, the `[<>]` toolbar button), not on other sites. Off-site links rot, and people shouldn't have to go off-site to help you. – T.J. Crowder Sep 18 '17 at 16:19
  • oops, sorry my bad.yes it accepts name as parameter – jass Sep 18 '17 at 16:20

2 Answers2

1

The prototype you should be applying to is (literally) Function not the name of the function. When you do this you can then execute callAfter on any defined function.

The below appears to do what you wanted.

function printName(name) {
  console.log('Name is: ' , name);
}

Object.defineProperty(Function.prototype, "callAfter", {
  value: function(delay, args) {
    var func = this;
    setTimeout(function(){
      func.apply(func,args);
    }, delay);
  }
});
printName("Instant");
printName.callAfter(3000,["After 3 seconds"]);

*(I'm using Object.defineProperty there so that callAfter isn't enumerable, which is frequently important when extending built-in prototypes.)*

You should be aware that extending built-in objects has some gotchas to be aware of.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Jamiec
  • 133,658
  • 13
  • 134
  • 193
-1

I think I have what you want working in this jsfiddle: https://jsfiddle.net/kd13ugwt/

function printName(name) {
  console.log('Name is: ' , name);
}

printName.callAfter = function(time, name) {
  setTimeout(function() {
    printName(name)
  }, time);
}

printName.callAfter(3000, 'foo');
TKoL
  • 13,158
  • 3
  • 39
  • 73