format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");上面的脚本就会返回
"And the papers want to know whose shirt you wear" 。在这里需要注意的是,即便在 format 函数定义中,我们仅定义了个名为 string 的参数。而 Javascript 不管函数自身定义的参数数量,它都允许我们向一个函数传递任意数量的参数,并将这些参数值保存到被调用函数的 arguments 对象中。
有种情况就是总是要有个输出的模板是相同的,为了节省每次是使用上面提到的 format 函数并指定重复的参数,我们可以使用 makeFunc 这个工具。它将返回一个匿名函数,并自动生成已经指定模板后的内容: 复制代码 代码如下: var majorTom = makeFunc(format, "This is Major Tom to ground control. I"m %1.");
你可以像这样重复指定 majorTom 函数: 复制代码 代码如下: majorTom("stepping through the door"); majorTom("floating in a most peculiar way");
那么当每次调用 majorTom 函数时,它都会使用第一个指定的参数填写已经指定的模板。例如上述的代码返回: 复制代码 代码如下: "This is Major Tom to ground control. I"m stepping through the door." "This is Major Tom to ground control. I"m floating in a most peculiar way."