javascript - call 和 apply的普通显示绑定为何说还是会丢失绑定,而bind不会?
PHP中文网
PHP中文网 2017-04-11 11:40:35
[JavaScript讨论组]

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

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
怪我咯

我认为.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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号