如3樓所說 大致上就是改變 sayColor 的 this 但跟objectSayColor 的 this無關 bind的原作大概像這樣 Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () { }, fBound = function () { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; };
里面结构大概是这样的:
Function.prototype.bind = function(obj){
var fn = this;
return function(){
fn.call(obj)
}
}
也就是说bind方法返回是一个函数,所以不能直接改成sayColor.bind(o);
但是可以改成sayColor.bind(o)();
call比bind多了一步是this指向改变之后调用了他(sayColor),
bind只是改变了this的指向,并没有调用。
这个方法会创建一个函数的实例,其this值会被绑定到传给bind()函数的值。调用就是fn()这种方式,主要是大括号的作用。
另外bind这个方法是一个新接口,旧版本并不支持。
两种执行后的结果:call是一个值,bind是一个引用,比较灵活,想调用调用不想调用就在那放着。
var objectSayColor = sayColor.bind(o);
也可以写成:sayColor.bind(o)();
sayColor.bind(o)这是一个引用,需要()来调用他,这样才会得到function sayColor() {
alert(this.color);
}这个结果。
其它参考:
http://book.douban.com/annotation/29054774/
大致上就是改變 sayColor 的 this
但跟objectSayColor 的 this無關
bind的原作大概像這樣
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
} var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () { },
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
}; fNOP.prototype = this.prototype;
fBound.prototype = new fNOP(); return fBound;
};