JavaScript - 对象字面量的优点

发布于 2024-08-07 23:37:57 字数 58 浏览 6 评论 0原文

我读过,我应该使用对象文字,而不是简单地编写一堆函数。

对象字面量有什么优点,有例子吗?

I've read that rather than simply writing a bunch of functions, I should use an object literal.

What are the advantages of object literal, with examples?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

痴骨ら 2024-08-14 23:37:57

正如 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)。页面上没有其他代码可以调用这些函数;他们确实是私人的。只有最后在 return 语句中导出的内容在作用域函数之外才可见。
  • 如果实现完全改变(例如 IE-vs-W3C 的东西,或者 SVG 与 Canvas 等),则可以根据环境轻松返回不同的函数。

返回不同函数的示例:

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 */);

As Russ Cam said, you avoid polluting the global namespace, which is very important in these days of combining scripts from multiple locations (TinyMCE, etc.).

As Alex Sexton said, it makes for good code organisation as well.

If you're using this technique, I'd suggest using the module pattern. This still uses object literals, but as the return value from a scoping function:

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
    };
})();

External use:

MyThingy.doSomethingCool();

The scoping function is wrapped around all of your functions, and then you call it immediately and store its return value. Advantages:

  • Functions are declared normally and therefore have names. (Whereas with the {name: function() { ... }} format, all of your functions are anonymous, even though the properties referencing them have names.) Names help tools help you, from showing call stacks in a debugger, to telling you what function threw an exception. (2015 Update: The latest JavaScript specification, ECMAScript 6th edition, defines a large number of ways the JavaScript engine must infer a function's name. One of those is when the function is assigned to a property as in our {name: function() { ... }} example. So as engines implement ES6, this reason will go away.)
  • Gives you the freedom of having private functions only used by your module (such as my internalSomething above). No other code on the page can call those functions; they're truly private. Only the ones you export at the end, in the return statement, are visible outside the scoping function.
  • Makes it easy to return different functions depending on environment, if the implementation just changes completely (such as IE-vs-W3C stuff, or SVG vs. Canvas, etc.).

Example of returning different functions:

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 */);
深海夜未眠 2024-08-14 23:37: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();

Using an object literal (a.k.a. object literal pattern) will not pollute the global namespace as severely as using many functions declared globally will, and also helps to organise code in a logical fashion

For example, this object literal

var obj = {
              find : function(elem) { /* find code */ },
              doSomething: function() { /* doSomething code */ },
              doSomethingElse: function() { /* doSomethingElse code */ }
          }

compared to

function find(elem) { /* find code */ },
function doSomething() { /* doSomething code */ },
function doSomethingElse() { /* doSomethingElse code */ }

will create only one property on the global object compared to three. You can then easily use the functions like so

obj.doSomething();
可爱暴击 2024-08-14 23:37:57

Rebecca Murphey 在今年的 jQuery 大会上做了关于对象文字的演讲。使用它们的最佳理由之一就是良好的代码组织。

这是丽贝卡关于对象文字模式的文章:http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/

Rebecca Murphey did a talk on Object Literals at this year's jQuery Conference. One of the best reasons to use them is simply good code organization.

Here is Rebecca's write up on the Object Literal Pattern : http://rmurphey.com/blog/2009/10/15/using-objects-to-organize-your-code/

泪冰清 2024-08-14 23:37:57

我一直使用对象文字,因为它们是组织代码的清晰方式。这就是为什么我不喜欢原型;太乱了。

正如前面答案中提到的那样,函数不会比对象文字更污染名称空间。

您可以轻松地编写像 Which 之类的文字,

var obj = {}
var find = function(elem) { /* Find code */ },
var doSomething = function() { /* doSomething code */ },
var doSomethingElse = function() { /* doSomethingElse code */ }

它会通过创建大量全局对象来污染,与函数相同。同样,你可以这样做:

(function() {
    function find(elem) { /* Find code */ },
    function doSomething() { /* doSomething code */ },
    function doSomethingElse() { /* doSomethingElse code */ }
})();

这不会创建那些全局对象(一切都是 JavaScript 中的对象)。

这样你仍然不会创建大量的全局对象。

在我看来,对象文字有两个优点。一是它们被许多插件(例如 jQuery)使用,因此人们更熟悉并且易于阅读。使它们可以轻松地将数据传递到插件中。创建公共和私有方法都很容易......

但它们可能很慢,因为每次创建对象的实例时,它的所有方法都会重复。据我了解,原型的情况并非如此,因为您拥有方法的一份副本,而新对象只是引用原型。

我当然可能是错的......

I’ve always used object literals because they are a clear way to organise code. Which is why I don't like prototype; it's too messy.

Functions don't pollute the name space as someone mentioned in previous answers any more than object literals.

You could easily write a literal like

var obj = {}
var find = function(elem) { /* Find code */ },
var doSomething = function() { /* doSomething code */ },
var doSomethingElse = function() { /* doSomethingElse code */ }

Which would pollute by creating lots of global objects, the same as the functions. Similarly you could do:

(function() {
    function find(elem) { /* Find code */ },
    function doSomething() { /* doSomething code */ },
    function doSomethingElse() { /* doSomethingElse code */ }
})();

Which would not create those global objects (everything is an object in JavaScript).

that way you still don't create loads of global objects.

To my mind object literals have two advantages. One they are used by many plugins such as jQuery so people are familier and they are easy to read. Making them easy to pass through data into a plugin. It's easy to create both public and private methods....

They can be slow though as every time you create an instance of the object all it's methods are duplicated. It's my understanding that that isn't the case with prototype as you have one copy of the methods and new ojects simply reference the prototype.

I could be wrong of course...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文