以下示例是JavaScript中創建和操作對象的一種方式,即使用new Object()
語法。另一種方法是創建一個對象文字。有沒有在JavasScript中使用`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>
可能重複[是JavaScript的「新」關鍵字被認爲是有害的?](http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful) – 2011-03-04 13:23:08
有沒有充分理由你不應該使用新的Object(),唯一的好處是通過使用{}來使用更少的代碼,那就是全部 – 2011-03-04 13:23:42
@KIvanov實際上,更少的代碼是一個非常好的理由:) – 2011-03-04 13:26:56