js插件定义事件中,this引用的实现模拟
在web项目中,经常会使用jquery和mui等js框架,之前只是按照API说明去按规则使用,比如在jq和mui中,事件处理函数中可以直接用this访问事件源,如下面的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../../js/jquery.min.js" ></script>
</head>
<body>
<button id="msg-btn">CLICK ME!</button>
</body>
<script>
$(document).ready(function(){
$("#msg-btn").click(function(){
console.log( this.id );
});
});
</script>
</html>
在界面触发了点击事件后,打印this.id信息如下:

很显然,此处的this指向了事件源这个对象,或者说,事件处理函数的执行上下文(作用域context)被隐式的指定为事件源。
最近在做闭包编程时发现,这一模式很像bind方法和call方法的应用场景(bind方法本质上就是通过call实现的,利用了call可以绑定执行上下文的特性),即就是给函数指定了运行时所挂载的对象!下面分别按照call和bind方式,尝试模拟了具体实现:
1.通过call模拟
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="test">hi</div>
</body>
<script>
var dom = document.querySelector("#test");
//通过定义自己的事件绑定函数,将事件处理函数的调用上下文指定为事件源,因此事件函数中的this
//即指向事件源,因此可以直接取其id等其他属性
dom.__proto__.myaddEventListener = function( evename, _callback){
this.addEventListener( evename, function(e){ _callback.call( e.target,e ); });
}
dom.myaddEventListener( 'click',function(e){
console.log( this.id );
console.log( this );
console.log( e );
} );
</script>
</html>
在界面上点击<div>标签,打印信息如下:

可见this,指向了实践源,可以像访问dom属性一样来访问this了。
2. 通过bind模拟
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="test">hi</div>
</body>
<script>
var dom = document.querySelector("#test");
dom.__proto__.myaddEventListener = function( evename, _callback){
this.addEventListener( evename, function(e){
var __callback = _callback.bind( e.target );
__callback( e );
});
}
dom.myaddEventListener( 'click',function(e){
console.log( this.id );
console.log( this );
console.log( e );
} );
</script>
</html>
在界面上点击<div>标签,打印信息如下:

与call的模拟效果一致。
end...
路漫漫其修远兮,吾将上下而求索。
May stars guide your way⭐⭐⭐

浙公网安备 33010602011771号