1

I got a script like this,

   var first_object = {
        num: 42
    };

    function multiply(mult) {
        return this.num * mult;
    }

    //Bind part
    Function.prototype.bind = function (obj) {
        var method = this,
        temp = function () { 
             return method.apply(obj, arguments);
        };
        return temp;
    }

    var first_multiply = multiply.bind(first_object);
    first_multiply(5); // returns 42 * 5

    alert(second_multiply(5));

My question is, in the Bind part, cause what i really need is just the result from

method.apply(obj, arguments);

I just make the Bind part code like

 Function.prototype.bind = function (obj) {
    var method = this,
    return method.apply(obj, arguments);
}

But this change causes error.. and I don't know why. What I guess is the reason I need a var temp to hold the function is, js doesn't know what will be returned by method.apply(obj, argument), which cannot be returned, but it knows temp is a var, which can be returned.

I don't know if my guess is correct and the real reason is.

EDIT This is the error looks like

0x800a138a - JavaScript runtime error: Function expected 
Ranger 22
  • 415
  • 4
  • 19
  • `var method = this,` should end with a semicolon – Amodar Apr 09 '17 at 06:43
  • 2
    @Amodar it should not, they declare 2 variables. – zerkms Apr 09 '17 at 06:59
  • 1
    "But this change causes error" --- any reason you did not provide the error message? – zerkms Apr 09 '17 at 07:00
  • @ zerkms This is the error, 0x800a138a - JavaScript runtime error: Function expected – Ranger 22 Apr 09 '17 at 07:29
  • Which statement causes it? – zerkms Apr 09 '17 at 07:31
  • @zerkms You're right, the first snippet he's declaring 2 vars which is valid. But he's getting the runtime error when he changes the bind part code (the last snippet), that's where he's doing a declaration, return. Unless this is something I was not aware you could do in Javascript. – Amodar Apr 09 '17 at 07:47
  • @Ranger22 although this question is closed, maybe this can help you further: https://jsfiddle.net/w38o0u2u/ – Amodar Apr 09 '17 at 07:51
  • @Amodar they are getting runtime error because they are calling something that is not a function. – zerkms Apr 09 '17 at 07:55

0 Answers0