javascript上下文this

js的四种调用方式:

一 作为函数的调用:

在严格模式下this,undefined,在非严格模式下指向全局window对象。

二 作为方法调用:

this通常指向调用的对象

三 作为构造函数的调用:

this指向新创建的对象

四 通过call,apply调用:

this指向call或者apply的第一个参数

箭头函数没有单独的this

所有函数均可使用bind方法,创建函数,并且绑定到bind方法传入的参数上,被绑定的函数与原始函数具有一致的行为。

    let obj1 = {
        whoAMi: function() {
            return this;
        }
    }
    let obj2 = {
        whoAMi: obj1.whoAMi
    }
    let iden = obj2.whoAMi;

    console.log(obj1.whoAMi());//obj1
    console.log(obj2.whoAMi());//obj2
    iden();//windows,方法调用,(strict undefined)
    obj1.whoAMi.call(obj2);//obj2

    function Fn() {
        this.whoAMi = () => {this;}
    }
    let obj1 = new Fn();
    let obj2 = {
        whoAMi: obj1.whoAMi
    } 

    obj1.whoAMi();//obj1
    obj2.whoAMi();//obj1,由于obj1是构造函数,this代表调用者

    function Fn() {
        this.whoAMi = function() {
            return this;
        }.bind(this);
    }

    let obj1 = new Fn();
    let obj2 = {
        whoAMi: obj1.whoAmi
    };

    obj1.whoAmi();//obj1
    obj2.whoAMi();//obj1

猜你喜欢

转载自www.cnblogs.com/intelwisd/p/9080355.html