[前端分析] JavaScript中的this

1、函數(shù)中this 總是指向調(diào)用的對(duì)象
2、箭頭函數(shù)中的this 指向上下文

this 說來說去 不過上面兩點(diǎn)??聪孪旅鎺讉€(gè)demo加深下理解

1、demo1

function f1 () {
    console.log(this)
}
function f2 () {
    'use strict'
    console.log(this)
}
f1() // window
f2() // undefined
const foo = {
    bar: 10,
    fn: function() {
       console.log(this)
       console.log(this.bar)
    }
}
var fn1 = foo.fn
fn1()

函數(shù)在瀏覽器全局環(huán)境中被簡單調(diào)用; this 指向window,嚴(yán)格模式為undefined

2、demo2

const person = {
    name: 'GGGG',
    brother: {
        name: 'HHHH',
        fn: function() {
            return this.name
        }
    }
}
console.log(person.brother.fn())

輸出HHHH; this 指向調(diào)用對(duì)象, 調(diào)用對(duì)象為 person.brother

const o1 = {
    text: 'o1',
    fn: function() {
        return this.text
    }
}
const o2 = {
    text: 'o2',
    fn: function() {
        return o1.fn()
    }
}
const o3 = {
    text: 'o3',
    fn: function() {
        var fn = o1.fn
        return fn()
    }
}

console.log(o1.fn())
console.log(o2.fn())
console.log(o3.fn())

輸出為 o1 o1 undefined; 第2個(gè)o1 實(shí)際內(nèi)部o1.fn 的調(diào)用對(duì)象為o1, 所以輸出o1; 第3個(gè)中內(nèi)部的fn 的調(diào)用對(duì)象實(shí)際為 window , 所以輸出為undefined

3、 demo3

const foo = {
    name: 'hhhhh',
    logName: function() {
        console.log(this.name)
    }
}
const bar = {
    name: 'mike'
}
console.log(foo.logName.call(bar))
const o1 = {
    text: 'o1',
    fn: function() {
        return this.text
    }
}
const o2 = {
    text: 'o2',
    fn: o1.fn
}

console.log(o2.fn())

改變函數(shù)中this 指向的兩種方法,一種方式為 call/apply/bind ; 另一種方式為 直接賦值

4、demo4

const foo = {  
    fn: function () {  
        setTimeout(() => {  
            console.log(this)
        })
    }  
} 
console.log(foo.fn())

// {fn: ?}

箭頭函數(shù)中的this 滿足第2條

5、demo5

function Foo() {
    this.bar = "hhhhh"
}
const instance = new Foo()
console.log(instance.bar)

構(gòu)造函數(shù)中的this行為:

  • 創(chuàng)建一個(gè)新的對(duì)象;
  • 將構(gòu)造函數(shù)的 this 指向這個(gè)新對(duì)象;
  • 為這個(gè)對(duì)象添加屬性、方法等;
  • 最終返回新對(duì)象。

以上過程同:

var obj  = {}
obj.__proto__ = Foo.prototype
Foo.call(obj)

構(gòu)造函數(shù)有顯示返回值時(shí):

function Foo(){
    this.user = "hhhhh"
    const o = {}
    return o
}
const instance = new Foo()
console.log(instance.user) 

輸出undefined; this指向o

function Foo(){
    this.user = "hhhhh"
    return 1
}
const instance = new Foo()
console.log(instance.user)

輸出hhhhh; this 指向?qū)嵗?br> 具體見:一道前端小題的簡單分析 最后一部分的解釋~~

hi~~~ 有幫助么, 點(diǎn)個(gè)贊吧~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容