我开始使用facebook javscript SDK,当我阅读源代码时,我发现了一件有趣的事情.
代码示例如下:
/**
* Annotates a function with a meta object
*/
function annotate(fn, meta) {
meta.superClass = fn.__superConstructor__;
fn.__TCmeta = meta;
return fn;
}
// export to global
__w = annotate;
/**
* when using the annotate function
*/
function sprintf(format) {
// function body
}
__w(sprintf, {"signature":"function(string)"}); // <-- what is the purpose of doing this?
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是用于什么?这样做有什么好处?
仅供参考,整个源代码在这里,你可以看到很多annotate()被使用
在"学习JavaScript设计模式"一书的第109页上,有一个让我困惑的代码示例.
jQuery.single = (function( o ){
var collection = jQuery([1]); // <-- i want to ask this line
return function( element) {
// give collection the element
collection[0] = element;
// return the collection
return collection;
}
})();
Run Code Online (Sandbox Code Playgroud)
该功能的使用是这样的:
$('div').on('click', function() {
var html = jQuery.single( this ).next().html();
console.log( html );
});
Run Code Online (Sandbox Code Playgroud)
更新: 谢谢你的回答.我查看了作者页面76字节的原始代码源,以获得更快的jQuery
var collection = jQuery([1]); // Fill with 1 item, to make sure length === 1
Run Code Online (Sandbox Code Playgroud)
现在我明白了.我希望"学习JavaScript设计模式"一书的作者在引用此代码示例时也可以添加此注释.
我正在读一本JavaScript语言的教科书.在我研究封闭主题的同时,我提出了以下问题.
考虑到这个功能:
function foo() {
extractPropsToCurrentContext({'prop1' : 'hello', 'prop2' : 123});
}
Run Code Online (Sandbox Code Playgroud)
我想要上面代码的结果,等于:
function foo() {
var prop1 = 'hello';
var prop2 = 123;
}
Run Code Online (Sandbox Code Playgroud)
那么,我的问题是,如何实现函数extractPropsToCurrentContext(/*Object*/)?
为了澄清,我想将对象的这些属性提取到执行上下文中,而不是在'this'指针下.(因此,那些提取的道具应该在该函数内部是私有的).
另外要澄清一点,你不能假设用'new'调用foo.(比如新的foo())
更新:
我的意思是,有没有可能我们可以使用任何hacky技巧来绕过浏览器的限制,更接近我们想要的结果?就像多年前一样,我们发明了JSONP用于跨域,长时间推送消息等等?