Jou*_*key 38 javascript object-literal
我读过它而不是简单地编写一堆函数,我应该使用object literal.
有人可以用例子来解释对象文字的优点,因为到目前为止我还不明白.
谢谢
T.J*_*der 66
正如Russ Cam所说,你避免污染全局命名空间,这在组合来自多个位置(TinyMCE等)的脚本的这些日子里非常重要.
正如Alex Sexton所说,它也是一个很好的代码组织.
如果你正在使用这种技术,我建议使用模块模式.这仍然使用对象文字,但作为范围函数的返回值:
var MyThingy = (function() {
function doSomethingCool() {
...
}
function internalSomething() {
....
}
function anotherNiftyThing() {
// Note that within the scoping function, functions can
// call each other direct.
doSomethingCool();
internalSomething();
}
return {
doSomethingCool: doSomethingCool,
anotherNiftyThing: anotherNiftyThing
};
})();
Run Code Online (Sandbox Code Playgroud)
外用:
MyThingy.doSomethingCool();
Run Code Online (Sandbox Code Playgroud)
范围函数包含所有函数,然后立即调用它并存储其返回值.好处:
{name: function() { ... }}格式,但所有函数都是匿名的,即使引用它们的属性具有名称.)名称帮助工具可帮助您显示调试器中的调用堆栈,以告诉您哪个函数引发了异常.(2015年更新:最新的JavaScript规范,ECMAScript第6版,定义了JavaScript引擎必须推断函数名称的大量方法.其中之一就是在我们的{name: function() { ... }}示例中将函数分配给属性时.因此引擎实现ES6这个理由会消失.)internalSomething上面).页面上没有其他代码可以调用这些函数; 他们真的很私密.在返回语句中,只有最后导出的那些在作用域范围外可见.返回不同函数的示例:
var MyUtils = (function() {
function hookViaAttach(element, eventName, handler) {
element.attachEvent('on' + eventName, handler);
}
function hookViaListener(element, eventName, handler) {
element.addEventListener(eventName, handler, false);
}
return {
hook: window.attachEvent ? hookViaAttach : hookViaListener
};
})();
MyUtils.hook(document.getElementById('foo'), 'click', /* handler goes here */);
Run Code Online (Sandbox Code Playgroud)
Rus*_*Cam 15
使用对象文字(也称为对象文字模式)不会像使用全局声明的许多函数那样严重污染全局命名空间,并且还有助于以逻辑方式组织代码
例如,这个对象文字
var obj = {
find : function(elem) { /* find code */ },
doSomething: function() { /* doSomething code */ },
doSomethingElse: function() { /* doSomethingElse code */ }
}
Run Code Online (Sandbox Code Playgroud)
相比
function find(elem) { /* find code */ },
function doSomething() { /* doSomething code */ },
function doSomethingElse() { /* doSomethingElse code */ }
Run Code Online (Sandbox Code Playgroud)
将在全局对象上仅创建一个属性,而不是三个.然后,您可以轻松使用这样的功能
obj.doSomething();
Run Code Online (Sandbox Code Playgroud)
Ale*_*ton 10
Rebecca Murphey在今年的jQuery大会上发表了关于Object Literals的演讲.使用它们的最佳理由之一就是良好的代码组织.
以下是Rebecca关于Object Literal Pattern的文章:http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/
| 归档时间: |
|
| 查看次数: |
23406 次 |
| 最近记录: |