一段代码看了很久也搞不清楚,似懂非懂。
打上断点,仔细琢磨,终于有一点豁然开朗的感觉。
此处记录一些不容易想明白的地方,仅供分析用。
// 检查调用时的this,如果this绑定到全局对象或者undefined,那就把指定的默认对象obj绑定到this,
// 否则不会修改this
// 此段代码还支持可选的柯里化
if(!Function.prototype.softBind) {
Function.prototype.softBind = function(obj) {
// obj = {name: "obj"}
var fn = this; // A处this
// fn = f foo()
var curried = [].slice.call(arguments , 1);
// arguemnts 第一个参数用于绑定this,因此不计入
var bound = function() {
return fn.apply(
// B处this
// 注意 执行 fooOBJ() 时,此处的this与A处的this不同,
// A处this指向foo函数,此处指向window
(!this || this === (window || global)) ?
obj : this,
curried.concat.apply(curried, arguments)
)
};
bound.prototype = Object.create(fn.prototype);
return bound;
}
}
function foo() {
console.log("name: " + this.name);
}
var obj = { name: 'obj' },
obj2 = { name: 'obj2' },
obj3 = { name: 'obj3' };
var fooOBJ = foo.softBind(obj);
fooOBJ(); // 此时B处this指向window
obj2.foo = foo.softBind(obj);
obj2.foo(); // 此时B处this指向obj2
fooOBJ.call(obj3); // 此时B处this指向obj3
setTimeout( obj2.foo, 10);
//setTimeout()函数实现和下面的伪代码类似:
function setTimeout(fn, delay) {
// 等待delay毫秒
fn();
}