【发布时间】:2010-01-26 02:25:28
【问题描述】:
我目前正在编写一些基于 John Resig -Simple JavaScript Inheritance 的代码。 而且我在初始化数组时遇到了一些麻烦。如果我将数组作为对象的属性并且在调用 init() 期间不初始化数组,则对数组所做的所有修改(如 push、unshift 等)都会影响对象的进一步创建。 我不知道我是否足够清楚,这里有一个例子:
<html>
<head>
<script type="text/javascript">
/*
insert all the John Resig code here
*/
var Person = Class.extend({
arrayTest:[],
init: function(){
},
arrayModif: function(){
this.arrayTest.push(4);
this.arrayTest.push(2);
}
});
function example(){
var a=new Person();
document.write("This is a before any modifications:"+a.arrayTest+"<br/>");
a.arrayModif();
document.write("This is a after modifications:"+a.arrayTest+"<br/>");
var b=new Person();
document.write("This is b after creation:"+b.arrayTest+"<br/>");
};
</script>
</head>
<body onload="example();">
</body>
</html>
它将有以下输出:
This is a before any modifications:
This is a after modifications:4,2
This is b after creation:4,2
我想知道是否有人知道如何修改 John Resig 代码以实现以下输出,而不在 init() 中添加任何内容:
This is a before any modifications:
This is a after modifications:4,2
This is b after creation:
谢谢。
【问题讨论】:
标签: javascript arrays