美文网首页
7 js之this

7 js之this

作者: 一枝妖孽 | 来源:发表于2018-05-29 20:39 被阅读0次

    js中的this具有多态性

    var i=0;
    
    function Person(){
        //谁调用这个方法,this便表示谁
        i++;
        alert(this+i);
    }
    
    //this便表示 window==========0
    //Person();
    
    function Student(){
        
    }
    
    Student.s=Person;
    Student.s();//this便表示Student对象==========1
    
    var jsonObj={
        getPerson:Person//Person是一个对象
        
    }
    jsonObj.getPerson();//this 代表 jsonObj 对象==========2
    
    /**
     * $("#aaa");JQuery对象
     * $("div"); JQuery对象
     */
    
    
    /**
     * 利用Call方法 和apply方法改变 this的指向
     */
    function SuperStudent(){
        
    }
    Person.call(Student);//Student.Person();==========3
    Person.apply(SuperStudent);//SuperStudent.Person();=========4
    
    /**
     * 如果有回调函数的情况
        回调函数中的this,调用者来确定
     */
    //$().ready(function(){
    //  this.a=5;
    //});
    
    function testCallBack(callBack){
        callBack.call(this);//该 this 指代 调用 testCallBack 的 指代对象 ,然后可以传递 给 callBack函数
            //callBack.apply(Person);
    }
    
    testCallBack(function(){
        alert("callback显示的内容"+this);//该this 为 回调函数function 中的 this
    });//============================================
    
    
    /**
     * $("a").each(function(){
        $(this)
        });
     * 
     */
    

    相关文章

      网友评论

          本文标题:7 js之this

          本文链接:https://www.haomeiwen.com/subject/kzzajftx.html