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 wele = say.magic('Hi, how are you?'); addTo(5) == 7; wele() == '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.
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 wele = say.magic('Hi, how are you?'); addTo(5) == 7; wele() == '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.
Share Improve this question edited Jan 25, 2016 at 14:08 Jeroen 64k47 gold badges228 silver badges366 bronze badges asked Jan 25, 2016 at 14:00 user2755996user2755996 1151 gold badge3 silver badges8 bronze badges2 Answers
Reset to default 2You 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 wele = say.magic('Hi, how are you?');
console.log(addTo(5) == 7);
console.log(wele() == 'Hi, how are you?');
Also you can look to Polyfill for bind function on MDN
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 wele = say.magic('Hi, how are you?');
addTo(5) == 7;
wele() == 'Hi, how are you?';