gpt4 book ai didi

javascript - 有理由不在 Javascript 中使用 `new Object()` 吗?

转载 作者:行者123 更新时间:2023-11-28 11:41:14 25 4
gpt4 key购买 nike

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

我记得在某处读过,但现在找不到它,因为某种原因应该避免使用“new Object()”在 JavaScript 中创建对象。

现在有理由像下面的代码一样使用new Object()吗?

<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>

最佳答案

就是有点丑。改为这样写:

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

它做同样的事情。

关于javascript - 有理由不在 Javascript 中使用 `new Object()` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5194220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com