js中的this

<!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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值