javascript - call 和 apply的普通显示绑定为何说还是会丢失绑定,而bind不会?

查看:120
本文介绍了javascript - call 和 apply的普通显示绑定为何说还是会丢失绑定,而bind不会?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

call 和 apply的普通显示绑定为何说还是会丢失绑定,而bind不会?

解决方案

我认为.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

这篇关于javascript - call 和 apply的普通显示绑定为何说还是会丢失绑定,而bind不会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆