Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2018-09-22]: JS链式调用 Calculator(10).add(5).sub(1).print() #10

Open
Lemonreds opened this issue Sep 22, 2018 · 0 comments
Open

Comments

@Lemonreds
Copy link
Owner

前言

这几天看到一道非常有意思的题目:Calculator(10).add(5).sub(1).print() 结果输出 14 ,要去实现一个这样的链式调用。使用过jquery的话一定不陌生这种链式调用的方式,而且还是jquery的一大特色,使用例子如:$("#some").css("width").css("color","green"),可以看到每次方法调用完成后,又返回了原有的对象,这样就达到了链式调用的目的。

关于实现

实际上我们可以通过原型链来实现这一个功能,将公用的方法挂在原型链上,每次调用公用的方法之后,返回原有实例,具体代码和需要注意的细节参下:

function Inner(number) {
    // 初始化
    this.number = number
}
Inner.prototype = {
    // 注意此处 constructor 是必须的
    // 重写某一个函数的 prototype 会导致覆盖而非修改 
    // constructor不指定会变成如下:
    // Inner.prototype.constructor === Object.prototype.constructor
    constructor: Inner,
    add: function (n) { // 此处不能使用箭头函数 导致this指向为 undefined
        this.number += n
        return this // 返回当前实例
    },
    sub: function (n) {
        this.number -= n
        return this
    },
    print: function () {
        console.log(this.number)
        return this
    }
}

// 入口
function Calculator(number) {
    // 题目使用 Calculator(10) 而不是 new Calculator(10)
    // 我们可以包裹一层 返回一个Inner实例
    return new Inner(number)
}

Calculator(10).add(5).sub(1).print()
// 输出:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant