您的位置:首页 > Web前端 > JavaScript

javascript中this的使用详解

2017-08-11 11:33 741 查看
<script>

    //this始终代表的是调用当前函数的那个对象

    //1.方法调用模式,this被绑定在对象obj上,对象的方法被执行时候,调用的this指向对象的属性,所以输出zyq

    var name=123;

    var obj={

        //对象属性

        name:"zyq",

        //对象方法

        printfName:function(){

            console.log(this.name); //输出zyq

            console.log(name);//输出123

        }

    };

    obj.printfName()//调用对象方法

    //2.函数调用模式,this是全局对象,浏览器环境下是window

    var name1="zyq";

    function printfName(){

        console.log(this.name1);//输出zyq

        console.log(name1);//输出zyq

    }

    printfName();

    //3.构造函数调用模式;用new 方法调用函数Obj,这个时候就创建了链接到函数的prototype成员的新对象,这个函数可叫做对象person的构造函数

    function Obj(){

        this.name=234;

    }

    var person = new Obj(); //实例化对象后,this绑定在对象person上了

    console.log(person.name); //输出234

    4.apply调用模式; js中函数也是对象,所有的函数有两个方法apply和call,这两个方法可让我们构建一个数组传递给调用函数,可用来改变this的值

    var name3="456";

    var person={

        name3:"hys"

    };

    function printf3Name(){

        console.log(this.name3);

    }

    printf3Name();//tnis代表window,输出456

    printf3Name.apply(person); //this代表对象person,输出hys

    printf3Name.apply(); //this代表window,输出456

    //综合以上实力

    //this是在函数执行时绑定的,不要被赋值给搞得眼花缭乱

    var name5="window";

    function showName(){

        console.log(this.name5);

    }

    var person5={

        name5:"kxy",

        sayName:showName

    }

    var person6={

        name5:"jake",

        sayName:function(){

            var fun=person5.sayName;

            fun();

        }

    }

    person5.sayName();  //对象person5的sayName方法调用了函数,所以this指向person5,所以输出kxy 

    person6.sayName();  //对象person6的syaName方法调用函数fun,最后是函数fun调用了函数showName,this指向window,所以输出window 

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js this