JS中的this指向

1、 普通函數: this指向 window

    function foo() {
        function fn() {
            console.log(this);
        }
        console.log(this); // window  只用函數的調用方法來判斷this的指向
    }
    foo();

2、構造函數: this指向實例化對象

    function Parent(name) {
        this.name = name;
        console.log(this);
    }
    var p1 = new Parent('zhangsan');
    var p2 = new Parent('lisi');

3、方法調用 :this指向函數的調用者

    function fun(val) {
        console.log(val);
        console.log(this);
        console.log(this.age);
        console.log(this === obj);
    }
    var obj = {age: '18'};
    obj.say = fun;
    fun();
    obj.say();

4、call和apply方法

    var name = 'global';
    var obj = {
        name: 'obj',
        dose: function () {
            this.name = 'dose';//當前的this指向obj(將obj.name的值改成dose)
            return function () {
                return this.name;//當前的this指向window
            }
        }
    };
    console.log(obj.dose()());//global
    console.log(obj.dose().call(obj));//dose
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章