总结篇(三) -- 你知道 log 出来的 this 是什么么

概述

函数中的 this 是一个很重要的知识点,如果能清楚的知道各种场景下函数中 this 所代表的值,那么对于我们去理解库 | 框架是很有帮助的,也可以让我们去运用一些更加高级的思想

this

this 的使用情况大致分为两种

  • 函数中
  • 对象的方法中
this === call | apply | bind 的第一个参数

在判断 this 的值的时候,进行相应的转化是很有必要的

严格模式 + 非严格模式

示例一

'use strict'
function fn( a, b ){
    console.log( this )
}
fn( 1, 2 )

上述中的 this 会打印出什么呢?

fn( 1, 2 ) === fn.call( undefined, 1, 2 ) === fn.apply( undefined, [1, 2] )

答案

  • 严格模式 ==> this === undefined
  • 非严格模式 ==> this === undefined == 浏览器转化 ==> window

对象方法

示例二

let obj = {
    fn: function( a, b ){
        console.log( this )
    },
    child: {
        fn2: function(){
            console.log( this )
        }
    }
}
obj.fn( 1, 2 )
obj.child.fn2()

上述中的 this 会打印出什么呢?

obj.fn( 1, 2 ) === obj.fn.call( obj, 1, 2 ) === obj.fn.apply( undefined, [ 1, 2 ] )  ==> this === obj
obj.child.fn2() === obj.child.fn2.call( obj.child )  ==> this === obj.child

示例三

let arr = []
for( let i = 0; i < 3; i++ ){
    arr[ i ] = function(){
        console.log( this )
    }
}
let fn = arr[ 0 ]
arr[ 0 ]
fn()

上述中的 this 会打印出什么呢?

arr[ 0 ] ==> arr 对象{ 0: fn, 1: fn, 2: fn } ==> arr.0 ==> arr.0.call( this ) ==> this === arr
fn() ==> fn.call( undefined ) ==> this === undefined == 浏览器转化 ==> window

bind

bind用法在之前有讲过,这个 API 就是返回一个函数 + 绑定 this

示例四

let obj = { a: 1 }
function fn(){
    console.log( this )
    console.log( this.a )
}
let newFn = fn.bind( obj )
newFn() 

上述中的 this 会打印出什么呢?

newFn() === fn.bind( obj )() ==> this === obj ==> this.a === 1

示例五

let obj = {
    container: document.querySeletor( 'body' )
    bind: function(){
        console.log( this )
        this.container.addEventListener( 'click', this.sayHello )
        this.container.addEventListener( 'click', this.sayHello.bind( this ) )
    },
    sayHello: function(){
        console.log( this )
    }
}
obj.bind()

上述中的 this 会打印出什么呢?

bind 中的 ` this ` ==> obj.bind.call( obj ) ==> this === obj
this.container.addEventListener( 'click', this.sayHello ) 当点击事件触发时,sayHello 打印出的 this ==> this === 绑定事件的元素(this.container) ==> this === obj.container
this.container.addEventListener( 'click', this.sayHello.bind( this ) ) 当点击事件触发时,sayHello 打印出的 this ==>  bind 绑定了 this[ this === obj ] ==> sayHello 打印出的 this === obj

箭头函数

箭头函数没有 this + arguments

示例六

let obj = {
    fn1: function(){
        console.log( this )
    },
    fn2() {
        console.log( this )
    },
    fn3: () => {
        console.log( this )
    }
}
obj.fn1()
obj.fn2()
obj.fn3()

上述中的 this 会打印出什么呢?

obj.fn1() === obj.fn1.call( obj ) ==> this === obj
obj.fn2() === obj.fn2.call( obj ) ==> this === obj
fn1 的写法 === fn2 的写法
obj.fn3() === obj.fn3.call( 与 obj 同级 this ) ==> this === window

示例七

let obj = {
    init() {
        console.log( this )
        let prop = {
            init: () => {
                console.log( this )
            },
            bind() {
                console.log( this )
            } 
        }
        prop.init()
        prop.bind()
    }
}
obj.init()

上述中的 this 会打印出什么呢?

let obj = {
    init() {
        console.log( this )  // 2.  this === obj
        let prop = {
            init: () => {
                console.log( this )  // 4. this === prop 同级 this ==> this === obj 
            },
            bind() {
                console.log( this )  // 6. this === prop
            } 
        }
        prop.init()  // 3. init() 是箭头函数 ==> prop.init.call( prop 同级 this )
        prop.bind()  // 5. bind 不是箭头函数 ==> prop.bind.call( prop )
    }
}
obj.init()  // 1.  === obj.init.call( obj )

示例八

let obj = {
    x: console.log( this )
    fn1() {
        console.log( this )
        setTimeout( function(){
            console.log( this )
        }, 10 )
    },
    fn2() {
        console.log( this )
        setTimeout( () => {
            console.log( this )
        }, 20 )
    },
    fn3() {
        console.log( this )
        setTimeout( function(){
            console.log( this )
        }.bind( this ), 30 )
    },
    fn4: () => {
        console.log( this )
        setTimeout( () => {
            console.log( this )
        }, 40 )
    }
}
obj.fn1()
obj.fn2()
obj.fn3()
obj.fn4()

obj.x 的值是什么?

上述中的 this 会打印出什么呢?

let obj = {
    x: console.log( this )  // console.log( this ) 的值是 undefined ==> obj.x === undefined  其中的 this === window
}

fn1()

fn1() {
    console.log( this )   // 2. this === obj
    setTimeout( function(){
        console.log( this )  
    }, 10 )
    // 3. 等价于
    // function fn(){
    //     console.log( this )  // 5. this === undefined == 浏览器转化 ==> window
    // }
    // 过 10s 执行函数 fn
    // fn()   // 4. fn 非箭头函数  fn.call( undefined ) 
}
obj.fn1()  // 1. fn1 非箭头函数  obj.fn1.call( obj )

fn2()

fn2() {
    console.log( this )   // 2. this === obj
    setTimeout( () => {
        console.log( this )  // 5. this === 上级 this  ==> this === obj
    }, 20 )
    // 3. 等价于
    // () => {
    //     console.log( this )
    // }
    // 过 20s 执行箭头函数
    // 箭头函数()  // 4. 箭头函数 箭头函数.call( 上级this )
}
obj.fn2()  // 1. fn2 非箭头函数  obj.fn2.call( obj )

fn3()

fn3() {
    console.log( this )  // 2.  this === obj
    setTimeout( function(){
        console.log( this )
    }.bind( this ), 30 )
    // 3.  等价于
    // function fn(){
    //     console.log( this )  // 5. this === obj
    // }.bind( this )
    // 过 30s 执行函数 fn
    // fn.bind(this)  // 4. fn 非箭头函数 + bind 绑定 this[ this === obj ]
}
obj.fn3()  // 1. fn3 非箭头函数  obj.fn3.call( obj )

fn4()

fn4: () => {
    console.log( this )  // 2. this === obj 同级 this  ==> this === window
    setTimeout( () => {
        console.log( this )
    }, 40 )
    // 3. 等价于
    // () => {
    //     console.log( this )  // 5. this === window
    // }
    // 过 40s 后执行箭头函数
    // 箭头函数()   // 4. 箭头函数  箭头函数.call( 上级 this )
}
obj.fn4() // 1. fn4 箭头函数  obj.fn4.call( obj 同级 this )

总结

判断函数中 this 步骤

  1. 查看调用函数的类型
  2. 箭头函数
    • 箭头函数.call( 上级 this )
    • obj.箭头函数.call( obj 同级 this )
  3. 非箭头函数
    • 非箭头函数.call( undefined )
    • obj.非箭头函数.call( obj )
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354

推荐阅读更多精彩内容

  •   引用类型的值(对象)是引用类型的一个实例。   在 ECMAscript 中,引用类型是一种数据结构,用于将数...
    霜天晓阅读 1,052评论 0 1
  • javascript中的this关键字 上一张初略版this分析导图先: this在英文中是一个指示代词,指示将要...
    程序不原阅读 382评论 0 1
  • 与其他语言相比,函数的this关键字在JavaScript中的表现略有不同,此外,在严格模式和非严格模式之间也会有...
    codingC阅读 574评论 0 0
  • 《我喜欢一个人去旅行》 如果人能够可以一直做自己喜欢的事,那该有多好。 如果那样的话,我喜欢一个人...
    小欧学长阅读 624评论 18 12
  • 欢迎关注幼儿说,用简书的妈咪,都是有品味的母亲 你是否经常遇到这样的情形: 让孩子将垃圾桶里的垃圾倒掉,TA“哦”...
    幼儿说阅读 631评论 1 1