Your code has several issues that need to be addressed. Firstly, attempting to instantiate something by calling a constructor function with your testObject
will result in a type error since it is not a function. To fix this, the testObject
should be defined like this:
var TestObject = function () {
this.value = "this is my initial value";
};
TestObject.prototype.setup = function () {
this.value = "foo";
};
It's important to note the use of an uppercase T
for the constructor function and how the setup
method is defined on the prototype
, which is more memory efficient compared to defining it as a property of the instance.
Now that TestObject
is a valid function, you can create instances using the new
operator:
var myFirstObject = new TestObject();
var mySecondObject = new TestObject();
By calling the setup
method on an instance of TestObject
, the changes will only apply to that specific instance because the value of this
inside the method refers to the calling instance:
myFirstObject.setup();
console.log(myFirstObject.value); // 'foo'
console.log(mySecondObject.value); // 'this is my initial value'