JavaScript this简介

来源:互联网 发布:linux jdk设置jvm内存 编辑:程序博客网 时间:2024/05/16 08:49
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script>        /**         * this 作为JavaScript的关键字,经常容易混淆其所代表的值,现总结如下:         * 情况一:全局函数         * 全局函数中this指向的是global对象         */        var x1 = 1;        function test1() {            console.log(this.x1);        }        test1();    //1        var y1 = 1;        function test2() {            this.y1 = 0;        }        test2();        console.log(this.y1);   //0        /**         * 情况二:某个对象的方法         */        function test3() {            console.log(this.x);        }        var o = {};        o.x = 1;        o.m = test3;        o.m();      //1        /**         * 情况三:作为构造函数         * 用new关键字,再调用function会生成一个新的对象,而this则指向这个对象         */        function test4() {            this.x = 1;        }        var b = new test4();        console.log(b.x);   //1        /**         * 情况四:apply 和 call 调用         * this将指向apply和call的第一个参数target         */        function test5() {            console.log(this.x);        }        var j1 = {};        var j2 = {};        j1.x = 1;        j2.x = 2;        j1.m = test5;        j1.m.apply(j2);     //2        j1.m.call(j2);      //2    </script></head><body></body></html>
输入结果:
0 0
原创粉丝点击