<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../js/jquery-1.8.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
function Person() {
alert(this);
}
//1 代表Window
Person();//相当于 Window.Person
//Object
//2 表示Student
function Student() {
}
Student.s = Person;
Student.s();//此时,Person中的this表示的是Student这个function
//3 this代表json对象
var jsonObj = {
getPerson:Person //Person是一个对象
};
jsonObj.getPerson();//Object,this表示一个json对象
//小结:this具有多态性
// 4 利用call和apply方法改变this的指向
function SuperStudent() {
}
Person.call(Student);//Student.Person(); --> this 表示Student函数
Person.apply(SuperStudent);//SuperStudent.Person(); --> this表示SuperStudent函数
//可见call和apply的作用是相同的。不同之处在于,call的第二个参数开始传递的当前调用函数的参数列表,而apply传递的是一个参数数组。
//如果有回调函数的情况
//回调函数中的this,由调用者来确定
function testCallback(callback) {
callback();//回调函数中的this代表Window对象
//callback.call(Person);//回调函数中的this代表Person对象,因为使用call改变了其中this的指向。
}
testCallback(function () {
alert(this);
});
</script>
</body>
</html>
js中的this
最新推荐文章于 2024-02-05 08:00:00 发布