扫码关注官方订阅号
代码基本结构如图~ bindLeftEvent作为initLeftMenu的callback函数,但是bindLeftEvent中this已经不是整个代码块中的this,要如何使用call、apply或者其他方法使得bindLeftEvent中的this为全局的this?
欢迎选择我的课程,让我们一起见证您的进步~~
有两种方法,一种是比较通用的方法,使用在外部定义个this变量,然后使用匿名函数,再使用apply就可以了,入下:
init:function(){ var self = this; self.initLeftMenu(function(){ self.bindLeftEvent.apply(self,arguments); }) }
第二种是es5才提供的新方法 ,使用Function.prototype.bind方法进行绑定,如下
init:function(){ var self = this; self.initLeftMenu(self.bindLeftEvent.bind(this)); }
if (!Function.prototype.bind) { Function.prototype.bind = function (context) { var oldArgs = [].slice.call(arguments).slice(1), fn = this; return function () { var newArgs = [].slice.call(arguments); fn.apply(context, oldArgs.concat(newArgs)); }; } } ({ //... init: function () { //...前面代码 self.initLeftMenu(self.bindLeftEvent.bind(self)); } //... })
不是可以传进去么?
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
有两种方法,一种是比较通用的方法,使用在外部定义个this变量,然后使用匿名函数,再使用apply就可以了,入下:
第二种是es5才提供的新方法 ,使用Function.prototype.bind方法进行绑定,如下
不是可以传进去么?