I read this article http://web.archive.org/web/20110725013125/http://www.digital-web.com/articles/scope_in_javascript/.
In the last example, he provided the code:
var first_object = {
num: 42
};
var second_object = {
num: 24
};
function multiply(mult) {
return this.num * mult;
}
Function.prototype.bind = function (obj) {
//console.log(this); -> TypeError: Object #<Object> has no method 'log'
var method = this,
temp = function () {
//console.log(this); -> RangeError: Maximum call stack size exceeded
return method.apply(obj, arguments);
};
return temp;
}
var first_multiply = multiply.bind(first_object);
console.log(first_multiply(5)); // returns 42 * 5
var second_multiply = multiply.bind(second_object);
console.log(second_multiply(5)); // returns 24 * 5
Although he explained it, I still don't understand several things.
First, why we need do method = this
, why this
refers to the multiply function here and why this
will change when the function temp is created on the next line? Second, why we need to create a function temp here? Third, I tried to print out the this by using console.log(). The strange thing is they both show some errors, could you tell me why?
PS: I used WebStorm IDE.
UPDATE: Please don't ignore the third question, why there are two errors when using console.log, thanks