7 js之this

2018-05-29  本文已影响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)
    });
 * 
 */
上一篇下一篇

猜你喜欢

热点阅读