this指向问题

### this指向问题
1. 普通函数
    ```js
    var name = '张三'
    function getPersonName() {
        console.log(this.name)
    }
    getPersonName() //张三

    //严格模式下 抑制this
    "use strict";
    var name = "张三"
    function getPersonName() {
        console.log(this.name)
    }
    getPersonName() // Cannot read property 'name' of undefined
    ```
2. 普通对象
    ```js
    var obj = {
        name: '张三',
        getPersonName:function() {
            console.log(this.name)
        }
    }
    obj.getPersonName(); //this指向obj
    var fn=obj.getPersonName;
    fn(); // 此时调用 fn 方法,this指向window 对象
    ```
3. 构造函数
    ```js
    function Person(name,age) {
        this.name = name;
        this.age = age;
    }
    var p = new Pweson('张三',19);
    console.log(p.name) //this 指向了该构造函数实例化出来的对象。

    //如果构造函数显式的返回一个对象,那么 this 则会指向该对象。
     function Person(name,age) {
        this.name = name;
        this.age = age;
        this.sex="男";
        return {
            sex : '女'
        }
    }
    var p = new Person("张三",19);
    console.log(p.sex)  //'女'
    //如果该函数不用 new 调用,当作普通函数执行,那么 this 依然指向全局对象。
    
    ```
4. call()或apply()
    > 通过调用函数的 call() 或 apply() 方法可动态的改变 this 的指向。
原文地址:https://www.cnblogs.com/zhupanpan/p/11375573.html