In JavaScript, I simulate classes like this:
function MyClass() {} // Constructor
MyClass.prototype.myField = "foo";
I thought I'd make the code more readable and save keystrokes by using the with
keyword:
function MyClass() {} // Constructor
with (MyClass.prototype)
{
myField = "foo";
myOtherField = "bar";
myMethod = // etc
}
But if I then create an instance and try to access any of those fields, they're undefined
. However, if I do with (MyClass.prototype)
and then try to read values from it, that works - it's only when I try to change them or create new fields that it fails. I'm assuming this is because with (myObject)
scopes you to a clone of myObject, not an actual reference to the original instance.
So, is there any way to get around this? Any way to produce the results I want, with or with out with
? Or am I doomed to writing out MyClass.prototype
over and over again?