Javascript - Copying array(by value) into prototype
I was trying to make a constructor function and within it, i had/wanted to place an array:
function Animal(s) {
this.myarr.push(s)
this.bark = function() {
console.log(this.myarr)
}
}
Animal.prototype = {
myarr: []
}
var a = new Animal('a');
a.bark()
var b = new Animal('b');
b.bark()
The problem is that the array will be passed by reference. The result will be:
["a"]
["a", "b"]
I then tried Dean Edwards base class:
var Animal = Base.extend({
constructor: function(s) {
this.some.push(s)
},
some: [],
bark: function() {
consol开发者_高级运维e.log(this.some)
}
});
var a = new Animal('a');
a.bark()
var b = new Animal('b');
b.bark()
The result was the same.
["a"]
["a", "b"]
I don't know if this is the way arrays should be handler in a javascript 'class' system... though i can re-initialize that property to [] every time i call the constructor.
So, does anyone know how to deal with this? Should i re-initialize the property(if it's an array)? Thanks in advanced.
Edit:
The problem here is that whenever the constructor is called(this.myarr.push(s) for example) myarr will point to the same array - that's why after a new instance the array will grow in size.
So:
var a = new Animal('a')
var b = new Animal('ab')
var c = new Animal('abc')
var d = new Animal('abcd')
will result to:
["a", "ab", "abc", "abcd"]
I want(without defining myarr inside the constructor) myarr to have a default value everytime i call the constructor(through new Animal(()) which should be [ ].
If you attach your array to the prototype of the constructor, this array will be available to all instances, so everything an instance does to it, is reflected in .myarr
in the other instances. If you want an array per instance, you should define it as a 'local' property, i.e. this.myarr
. What you can do is define a method in the prototype that pushes a value into this.myarr
.
So your constructor function (classes are non extistent in javascript) could look like:
function Animal(s) {
this.myarr = [];
this.bark = function() {
console.log(this.myarr)
}
this.myarrAdd(s);
}
Animal.prototype = {
myarrAdd: function(val){this.myarr.push(val); return this;}
}
精彩评论