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...

posted @   sophel  阅读(401)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示