admin管理员组文章数量:1384770
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?';
本文标签: javascriptGeneric functionStack Overflow
版权声明:本文标题:javascript - Generic function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744513723a2610032.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论