鍍金池/ 問答/HTML/ 函數(shù)末尾return this 實現(xiàn)鏈式調用的原理是什么

函數(shù)末尾return this 實現(xiàn)鏈式調用的原理是什么

想知道為什么return this 之后就能實現(xiàn)鏈式調用,每一次的this都指向了哪?

回答
編輯回答
葬憶

this指向了含有這些方法的對象。不能理解的話你可以拆解開來看看。

lazyMan = {
    sleep() {
        console.log('sleep')
        return this
    },
    eat() {
        console.log('eat')
        return this
    },
    study() {
        console.log('eat')
        return this
    }
}

lazyMan.sleep().eat().study()

看成這樣: 
let temp
temp = lazyMan.sleep() // return this  所以 temp 指向了lazyMan
temp = temp.eat() // return this  所以 temp 指向了lazyMan
temp = temp.study() // return this  所以 temp 指向了lazyMan
2018年9月3日 07:51
編輯回答
吢涼

手寫了一個小計算器,可以理解一下

calc = {
    i: 0,
    init(n) {
        this.i = n;
        return this;
    },
    add(n) {
        this.i += n;
        return this
    },
    minus(n) {
        this.i -= n;
        return this
    },
    multiply(n) {
        this.i *= n;
        return this
    },
    result() {
        return this.i
    }
}

clipboard.png

由于this總是返回調用當前函數(shù)的對象,因此當我們把函數(shù)封裝在對象中時,在函數(shù)中return this時返回的是當前調用這個函數(shù)的對象,在上例中返回的就是calc對象。

又因為calc對象中又包含了多個函數(shù),因此可以繼續(xù)調用下去。只要函數(shù)中返回的是this,這個鏈式調用就可以一直進行下去~

2018年2月28日 08:48
編輯回答
尛曖昧

你通過當前對象實例調用,那么this就是當前對象,當然對象包含它的方法,return this 后那么還是當前對象,自然可以鏈式調用當前對象的其他方法。

在JavaScript中對象是作為引用被傳遞的。所以你可以讓每個方法都傳回對象的引用。
如果讓一個類的每個方法都返回this值,那么它就成了一個支持方法的鏈式調用的類。

2017年12月1日 10:47
編輯回答
何蘇葉

先搞清楚this指的什么

2017年4月1日 13:29