我已经读过了,我应该使用对象字面,而不是简单地编写一堆函数。
有没有人能用例子解释一下对象字面量的优点,因为到目前为止我还不明白。
谢谢
发布于 2009-10-21 19:25:41
正如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
};
})();
外部使用:
MyThingy.doSomethingCool();
作用域函数被包装在所有函数周围,然后立即调用它并存储它的返回值。优势:
{name: function() { ... }}
格式,所有函数都是匿名的,即使引用它们的属性有名称。)名称帮助工具可以帮助您,从在调试器中显示调用堆栈到告诉您哪个函数抛出异常。(2015年更新:最新的JavaScript规范,ECMAScript第6版,定义了JavaScript引擎必须推断函数名称的大量方法。其中之一是当函数被赋值给一个属性时,如我们的{name: function() { ... }}
示例所示。因此,当引擎实现ES6时,这个理由将不复存在。)internalSomething
)。页面上的任何其他代码都不能调用这些函数;它们是真正私有的。只有您在返回语句末尾导出的函数在作用域function.返回不同函数的示例:
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 */);
发布于 2009-10-21 19:07:57
使用对象文字(也称为对象文字模式)将不会像使用许多全局声明的函数那样严重污染全局命名空间,并且还有助于以逻辑方式组织代码
例如,此对象文字
var obj = {
find : function(elem) { /* find code */ },
doSomething: function() { /* doSomething code */ },
doSomethingElse: function() { /* doSomethingElse code */ }
}
与
function find(elem) { /* find code */ },
function doSomething() { /* doSomething code */ },
function doSomethingElse() { /* doSomethingElse code */ }
将只在全局对象上创建一个属性,而不是三个。然后,您可以很容易地使用下面的函数
obj.doSomething();
发布于 2009-10-21 19:09:23
Rebecca Murphey在今年的jQuery会议上做了一个关于对象字面量的演讲。使用它们的一个最好的原因就是良好的代码组织。
下面是Rebecca关于Object文字模式的文章:http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/
https://stackoverflow.com/questions/1600130
复制相似问题