在不带括号的情况下调用对象函数时,它如何显示自定义消息而不是返回整个函数?

When calling a object function without the parenthesis, how could it display a custom message instead of returning entire function?

我正在创建一个设计独特的 Javascript API,名为 Javascript-X。我没有使用传统方法制作 API,而是使用对象树在单个变量内部创建整个 API。

这看起来不错,“$jx.ex()”returns 'Hello World',但是如果您键入“$jx.ex”,它 returns整个功能。 运行 要查看的代码片段。

问题是,您可以自定义在键入“$jx.ex”时显示的消息吗?

$jx = {
  ex: function() {
    return ('Hello World.')
  }
};
console.log($jx.ex());
console.log($jx.ex.toString())

When calling a object function without the parenthesis, how could it display a custom message instead of returning entire function?

引用一个不带括号的对象函数时,除非你使用new,否则你不会调用它,你只是在引用它。例如:

// There are no function calls here
var x = $jx.ex;

如果您的 API 的用户执行上述操作,x 将是函数的引用,而不是字符串。

The question is, can you customize the message that displays when you type "$jx.ex"?

如果您在控制台中执行此操作并看到整个函数,则可能是控制台被强制转换为字符串(调用 toString),或者可能是控制台在低等级。如果是前者,我们可以通过给函数一个新的 toString:

来覆盖它

$jx = {
  ex: function() {
    return ('Hello World.')
  }
};
$jx.ex.toString = function() {
    return "This is the custom 'message'.";
};
console.log($jx.ex());           // A call
console.log($jx.ex);             // Not a call, results will
                                 // vary from console to console
console.log($jx.ex.toString());  // toString directly
console.log(String($jx.ex));     // toString indirectly

考虑下面的例子:

function Multiply(operator, operand) {
    return operator * operand;
}

This could equally be written:

Multiply = function(operator, operand) {
    return operator * operand;
}

虽然在第一个示例中,含义可能并不明显,但第二个示例更清楚地表明我们正在将一个具有 2 个参数的函数分配给一个名为 Multiply 的变量,这种函数作为赋值的概念很常见整个 javascript。这是函数 "first class citizens" 这一事实的一个小演示,也就是说,它们可以像传递值一样传递。

所以现在要区分赋值:

var operator = 3;
var operand = 4;
var ret = Multiply(operator, operand);

在定义 ret 变量时,执行乘法并分配 return 值 - ret 等于 12。

让我们换一种方式再试一次:

var operator = 3;
var operand = 4;
var ret = Multiply;

现在,在定义 ret 时,ret 成为您的 Multiply 函数,而不是从您的 Multiply 函数获得的结果。调用 ret() 将导致您的 Multiply 函数被执行,您可以像调用 Multiply(operator, operand):

一样调用它
var out = ret(3, 4);

相同
var out = Multiply(3, 4);