博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javascript上下文this
阅读量:4580 次
发布时间:2019-06-09

本文共 1011 字,大约阅读时间需要 3 分钟。

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

转载于:https://www.cnblogs.com/intelwisd/p/9080355.html

你可能感兴趣的文章