函数末尾return this 实现链式调用的原理是什么

想知道为什么return this 之后就能实现链式调用,每一次的this都指向了哪?

阅读 3.9k
4 个回答

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

手写了一个小计算器,可以理解一下

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总是返回调用当前函数的对象,因此当我们把函数封装在对象中时,在函数中return this时返回的是当前调用这个函数的对象,在上例中返回的就是calc对象。

又因为calc对象中又包含了多个函数,因此可以继续调用下去。只要函数中返回的是this,这个链式调用就可以一直进行下去~

你通过当前对象实例调用,那么this就是当前对象,当然对象包含它的方法,return this 后那么还是当前对象,自然可以链式调用当前对象的其他方法。

在JavaScript中对象是作为引用被传递的。所以你可以让每个方法都传回对象的引用。
如果让一个类的每个方法都返回this值,那么它就成了一个支持方法的链式调用的类。

先搞清楚this指的什么

推荐问题