zoukankan      html  css  js  c++  java
  • 一个简单插件this传值的跟踪

    <!DOCUTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
        <title>在封装函数的过程中,确保this的正确传递</title>
    </head>
    
    <body>
        <div class="box"></div>
    </body>
    <style>
        .box{
            100px;
            height:100px;
            background:orange;
        }
        .box:hover{
            background: #50f573;
        }
    </style>
    <script>
    var Nico = function(box,str){
        //4.实例化时被调用,dom对象被赋值给this.$box公共变量
        //rose字符串被赋值给this.str公共变量
        this.$box = box;
        this.str = str;
    }
    Nico.prototype = {
        constructor:Nico,//构造函数
        params:'',
        message:function(){
            //6.事件监听。鼠标点击,回调函数bindthis被调起,传入this.fndown方法及2中的this
            this.$box.on('mousedown',this.bindthis(this.fndown,this));
            //8.返回来的最终结果是fn.apply(obj,arguments);fn被赋值为this.fndown,obj为this
        },
        _message:function(){
            var _this = this;
            _this.$box.on('mousedown',function(){
                return _this.fndown.apply(_this);
            })
        },
        fndown:function(){
            // console.dir(arguments);
            this.params = this.str + ', uuuuuuu.';
            this.$box.on('mouseup',this.bindthis(this.fnup,this));
            //9.params被赋值,继续调用bindthis进行this绑定
        },
        fnup:function(){
            console.log(this.params);
            //打印params
            this.$box.off();
            //off() 方法通常用于移除通过 on() 方法添加的事件处理程序。
            this.$box.on('mouseup',this.bindthis(this.fnup,this));
            //监听mouseup事件,绑定this到自身。不添加则只执行一次
        },
        bindthis:function(fn,obj){
            //7.传入this.fndwon方法和this,内建this为传入的this
            //返回一个匿名回调函数并立即执行
            return function(){
                console.dir(arguments);
                //经跟踪arguments是点击事件n.Event
                console.log("
    ");
                return fn.apply(obj);
            }
        }
    }
    
    $.fn.mess = function(str){
        //2.形参str被赋值实参,arguments为['rose']
        //this被赋值为.box jquery对象
        var nic = new Nico($(this),str);
        //3.创建一个实例,并给构造函数传入被转换为jquery对象的dom元素和实参
        return nic.message();
        //5.返回 实例调用message函数后的结果到客户端
    }
    
    $(function(){
        $('.box').mess('rose');
        //1.调用开始,class为box的dom元素是调用对象,即后面this将绑定的对象。
        //给mess传入rose字符串
    })
    </script>
    </html>
  • 相关阅读:
    python使用数据库的一些操作
    正则表达式整理
    tomcat启动成功但是访问不到官网
    控制反转 依赖注入 AOP 和 IOC
    abstract 和 interface区别
    input文本框 鼠标点击默认消失,不输入离开鼠标恢复默认值
    声明式管理事务:基于AspectJ的xml方式
    使用注解配置声明式事务
    spring事物 (mu课)
    oracle表之数据类型
  • 原文地址:https://www.cnblogs.com/jiangtian/p/6323482.html
Copyright © 2011-2022 走看看