我认为.call(obj) 和 .apply 是这样的。找到方法。把方法的this指向传进去的对象obj。执行。 .bind更像是。找到方法然后返回一个 function.call(obj)这样的东西 举例子就是 function demo(){ console.log(this.x); } window.x = "window"; demo();// demo.call({x:"call"});// demo.apply({x:"apply"});// demo.bind({x:"bind"}); //function LNBind(fun,obj){return function(){fun.call(obj)}}; //LNBind(demo,{x:"LNBind"})(); //本来想写一个仿原生的,但是居然写不出来了。。。我在想想,回来补坑 //从网上搜索了一个,原理和我的一样。只不过不知道为什么我用obj写的时候没出来 1 if (!Function.prototype.bind) { 2 Function.prototype.bind = function (oThis) { 3 if (typeof this !== "function") { 4 // closest thing possible to the ECMAScript 5 internal IsCallable function 5 throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); 6 } 7 8 var aArgs = Array.prototype.slice.call(arguments, 1), 9 fToBind = this, 10 fNOP = function () {}, 11 fBound = function () { 12 return fToBind.apply(this instanceof fNOP && oThis 13 ? this 14 : oThis || window, 15 aArgs.concat(Array.prototype.slice.call(arguments))); 16 }; 17 18 fNOP.prototype = this.prototype; 19 fBound.prototype = new fNOP(); 20 21 return fBound; 22 }; 23 } //来源 http://www.cnblogs.com/admos/p/4455922.html
回调函数丢失this绑定function foo() { console.log(this.a); } function doFoo(fn) { fn(); } var obj = { a: 2, foo: foo } var a = "oops, global"; doFoo.call(obj, obj.foo); // 输出oops, global
我认为.call(obj) 和 .apply 是这样的。找到方法。把方法的this指向传进去的对象obj。执行。
.bind更像是。找到方法然后返回一个 function.call(obj)这样的东西
举例子就是