NodeJS 模块、Chalk 的链接语法是如何工作的?

How does NodeJS module, Chalk's, chaining syntax work?

我不明白 Chalk 的(NodeJS 模块)语法是如何工作的(这让我很困扰)。我已经广泛搜索了答案,但我没有任何运气,并且可能不知道我需要寻找的技术术语。我已经尝试在 Whosebug 上查找 chalk 特定的问题,“方法链接”,“原型”等。尝试查看 Chalk 的源代码,但似乎仍然无法找到我的答案。有问题的语法是:

// Code snippet from the Chalk NPM Page.
log(chalk.blue.bgRed.bold('Hello world!'));
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

我熟悉方法链,也熟悉在对象中存储函数。我的主要问题是:chalk.blue 如何同时成为 属性 和函数?

如有任何帮助,将不胜感激。无论是完整的解释还是正确的方向推动。

The main question I have is: how can chalk.blue be a property and a function at the same time?

在 Javascript 中,函数是一个对象,因此除了可以作为 chalk.blue() 调用外,它还可以具有 chalk.blue.bgRed.

等属性

例如,您可以这样做:

function callMe() {
    console.log("callMe");    
}

callMe.greeting = "hello";

callMe();
console.log(callMe.greeting);

然后,对于无限链,您可以使用 getters 创建无限的对象链。

Chalk 可能正在使用 getters and setters 来“调用”适当的函数。下面是一个简单的例子:

let a = function (txt) {
    console.log(a.buffer + txt);
    a.buffer = ''
}

a.buffer = '';

Object.defineProperty(a,'b',{
    get: function(){
        this.buffer += '<B>';
        return this
    }
});

Object.defineProperty(a,'c',{
    get: function(){
        this.buffer += '<C>';
        return this
    }
});

Object.defineProperty(a,'d',{
    get: function(){
        this.buffer += '<D>';
        return this
    }
});

基本上它只是常规的方法链接,但使用 getters 使它变得花哨!另一个技巧是使基础对象成为函数而不是常规对象,这样 this 你 return 就可以调用了。

现在您可以:

a.b.c.b.d('hello'); // prints <B><C><B><D>hello