J
jonnys5k
I wanted to add an object as a prototype to separate my methods more
nicely, however, I ran into a couple of problems. Apart from the
obvious "scope" issues I found that any instances of my class shared
the objects methods and properties.
I realise (now) that this is actually how prototypes work, they share
functions and objects rather than create new instances of them for
every "class", but is there any way around it? (or shouldn't I be doing
things like this at all?)
Example:
var class = function()
{
[...]
}
class.prototype.method = function()
{
[...]
}
class.prototype.object = {
randomNumber : Math.random()*255,
method : function() {
{
return this.randomNumber;
}
}
var blah1 = new class();
var blah2 = new class();
blah1.object.method() // returns 42
blah2.object.method() // returns 42, the same!
nicely, however, I ran into a couple of problems. Apart from the
obvious "scope" issues I found that any instances of my class shared
the objects methods and properties.
I realise (now) that this is actually how prototypes work, they share
functions and objects rather than create new instances of them for
every "class", but is there any way around it? (or shouldn't I be doing
things like this at all?)
Example:
var class = function()
{
[...]
}
class.prototype.method = function()
{
[...]
}
class.prototype.object = {
randomNumber : Math.random()*255,
method : function() {
{
return this.randomNumber;
}
}
var blah1 = new class();
var blah2 = new class();
blah1.object.method() // returns 42
blah2.object.method() // returns 42, the same!