var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
bob.setAge(50);
console.log(bob.age);
This works, but when I try to do this
var setAge = function (newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 30;
bob.setAge(50);
console.log(bob.age);
it returns "bob.setAge() is not a function" in the compiler?
The second example doesn't work because you haven't defined setAge, as you have here
bob.setAge = setAge;
. You created anew Object()
, not a new custom-defined object. You're using sorta hybrid code... this is how you could do "classes"You have created an object 'Bob', but that object does not have the method 'setAge' until you assign it.
You may want to look into doing something like this in your design: