有没有理由不在JavasScript中使用`new Object()`? [英] Is there a reason not to use `new Object()` in JavasScript?

查看:106
本文介绍了有没有理由不在JavasScript中使用`new Object()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例是JavaScript中用于创建和操作对象的一种方法,即使用 new Object()语法。另一种方法是创建一个对象文字。

The following example is one way in JavaScript to create and manipulate objects, i.e. with the new Object() syntax. The other way is by creating an object literal.

我记得在某个地方读过但现在无法找到它使用new Object()在JavaScript中创建对象应该因某种原因要避免。

I remember reading somewhere but can't find it now that using "new Object()" to create objects in JavaScript should be avoided for some reason.

现在是否有理由使用 new Object(),如下面的代码?

Is there a reason now to use new Object() as in the following code?

<html>
    <head>
        <title>Test Page</title>
        <script type="text/javascript">
            window.onload = function() {

                var layout = new Object();
                layout.idCode = 'simple';
                layout.title = 'Simple Layout';
                layout.content = '';
                layout.width = 400;
                layout.display = function() {
                    return '<div style="background-color: #eee; width:'+this.width+'">'+this.content+'</div>'
                };

                layout.width = 200;
                layout.content = 'This is the new content';

                document.getElementById('output').innerHTML = layout.display();
            };
        </script>
    </head>
    <body>
        <div id="output"></div>
    </body>
</html>


推荐答案

这有点难看。改为写下:

It's just a bit ugly. Write this instead:

window.onload = function() {

    var layout = {
        idCode:   'simple',
        title:    'Simple Layout',
        content:  '',
        width:    400,
        display:  function() {
            return '<div style="background-color: #eee; width:'+this.width+'">'+this.content+'</div>'
        },

        width:    200,
        content:  'This is the new content'
    };
    document.getElementById('output').innerHTML = layout.display();
};

也做同样的事情。

这篇关于有没有理由不在JavasScript中使用`new Object()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆