js this

来源:互联网 发布:腾讯网络大电影 编辑:程序博客网 时间:2024/06/07 09:47
/**
 * 1、this表示window
 */
function Person(){
alert(this);
}
//Person(); //火狐弹出window


/**
 * 2、this代表student
 * 输出:
 * function Student(){
 *
 * }
 */
function Student(){

}
Student.s = Person;
//Student.s(); //Student是调用者,而Student是一个函数


/**
 * 3、this代表该json对象
 */
var jsonObj = {
getPerson:Person  
};
//jsonObj.getPerson(); //jsonObj是一个对象




/**
 * 4、利用call方法和apply方法改变this的指向
 */
function SuperStudent(){

}
//Person.call(Student); //Person的this指向Student函数
//Person.apply(SuperStudent);  //Person的this指向SuperStudent函数
/**
 * 5、回调函数:函数内部定义函数,外面调用
 *  *    $().ready(function(){
 *     this.a = 5;
 *    });
 *    回调函数中的this,调用者来确定
 */
function testCallback(callback){
//callback.call(this);//回调函数的this是window
callback.apply(Person);
}


testCallback(function(){
alert(this);//该this为回调函数中的this

});

总结:谁调用当前函数,谁就是this,call方法和apply方法改变this的指向












0 0
原创粉丝点击