最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Generic function? - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 2

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 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?';
发布评论

评论列表(0)

  1. 暂无评论