I'm trying to figure out the answer to this question:
Without using Javascript's bind function, implement the magic function so that:
var add = function(a, b) { return a + b; } var addTo = add.magic(2); var say = function(something) { return something; } var welcome = say.magic('Hi, how are you?'); addTo(5) == 7; welcome() == 'Hi, how are you?';
I think I need to use call or apply but I just don't know, if someone could point me in the right direction or provide some literature it would be much appreciated.
You can use closure, and apply function
Function.prototype.magic = function(){
var self = this;
var args = Array.from(arguments);
return function(){
return self.apply(null, args.concat(Array.from(arguments)));
}
}
var add = function(a, b) { return a + b; }
var addTo = add.magic(2);
var say = function(something) { return something; }
var welcome = say.magic('Hi, how are you?');
console.log(addTo(5) == 7);
console.log(welcome() == 'Hi, how are you?');
Please see below code:
Object.prototype.magic = function (message) {
alert(message);
}
var add = function (a, b) { return a + b; }
var addTo = add.magic(2);
var say = function (something) { return something; }
var welcome = say.magic('Hi, how are you?');
addTo(5) == 7;
welcome() == 'Hi, how are you?';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With