构造函数里的this指向

会有一股神秘感。 提交于 2020-03-06 13:37:02
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>构造函数里的this指向</title>
</head>
<body>
    <script>
        /*
        * this 在面向对象里面的this 构造函数里面的this在构造函数里面,
        * 当new 函数的时候,这个函数就变成了构造函数this单一的就是指向实例化对象
        * 但是可以通过call、apply、bind去改变构造函数里的this指向
        * */
        function Person(){
            this.name = 'Tom';
            this.age = 20;
            this.move = function(){
                console.log(this);  //指向Person
                // play(); //原本指向window
                play.call(this);  //改变this指向,指向Person
                this.eat = function(){
                    console.log('eat的方法');
                    console.log(this);
                }
            }
        }
        function play(){
            console.log(this)
        }
        var p1 = new Person();
        p1.move();
        p1.eat();
        //必须调用了move()方法后才可以调用eat()方法
        /*
        * 闭包中的this
        * 闭包函数----将方法和变量私有化并公开接口,这个接口就是函数
        * */
        function closer() {
            var abc = 10;
            function test1(){
                console.log('我是test1');
                console.log(this)
            }
            function test2(){
                console.log('我是test2');
                console.log(this)
            }
            return {test1,test2}
        }
        var test = closer();
        console.log(test); //结果是{test1: ƒ, test2: ƒ}
        test.test2();  //this指向的仍然是{test1: ƒ, test2: ƒ}

    //    练习
        console.log('===============');
        function closer1(){
            function test3(){
                console.log('我是test3');
                console.log(this);  //this指向{test3}
                function test4(){
                    console.log('我是test4');
                    console.log(this); //this指向window
                }
                return test4.bind(this)  //this指向了{test3}
            }
            return {test3}
        }
        console.log(closer1()); //得到的是一个对象 {test3: ƒ}
        closer1().test3()();
    </script>
</body>
</html>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!