我正在查看Arrowlets 源代码,并在顶部附近找到了此部分:
/*
* Box: a temporary (singleton) place to put stuff. Used as a helper for constructors with variadic arguments.
*/
function Box(content) {
Box.single.content = content;
return Box.single;
}
/* JavaScript hackery based on the strange semantics of "new":
* - Box() assigns Box.single.value, so Box.single has to be defined;
* - properties can be assigned to numbers (but have no effect);
* - when Box.single = 1 (or any non-Object), "new Box" returns "this". */
Box.single = 1;
Box.single = new Box;
Box.prototype.toString = function Box$prototype$toString() {
return "[Box " + this.content + "]";
}
我还查看了Box
's 在源代码中的一些用法,似乎这是传递多个参数的另一种方式,但我真的不明白如何。此外,评论指出:
当 Box.single = 1(或任何非对象)时,“new Box”返回“this”。
但我认为每当使用 , 调用构造函数时new
,this
都会返回。有人可以向我解释一下吗?
更新:
我很难理解为什么Box.single
必须将这种方法设置为非对象才能工作,以及使用new
运算符的诡计获得了什么。来自 NodeJS repl 的示例:
否new
并使用非对象
> function Box(content) {
... Box.single.content = content;
... return Box.single;
... }
Box.single = {}; // NOTE: Setting Box.Single to an Object
{}
> //NOTE: Not using the "new" operator at all
undefined
> Box(23)
{ content: 23 }
> Box.single
{ content: 23 }
> Box({'name': 'John'})
{ content: { name: 'John' } }
> Box.single
{ content: { name: 'John' } }
使用new
和对象
> function Box(content) {
... Box.single.content = content;
... return Box.single;
... }
undefined
> Box.single = {}; // Setting Box.single to an object
{}
> Box.single = new Box; // Using the new operator
{ content: undefined }
> Box({'name': 'John'})
{ content: { name: 'John' } }
> Box.single
{ content: { name: 'John' } }
而不是使用Arrowlets的方法:
> function Box(content) {
... Box.single.content = content;
... return Box.single;
... }
undefined
> Box.single = 1; // Setting Box.single to a Non-Object
1
> Box.single = new Box; // Using the new operator
{}
> Box(23)
{ content: 23 }
> Box({'name': 'John'})
{ content: { name: 'John' } }
> Box.single
{ content: { name: 'John' } }
看起来箭头方法只是完成简单事情的一种复杂方式。我错过了什么?