0
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?

John Doe
  • 13
  • 2
  • 2
    `bob` is a `new Object`, it does'nt magically have a `setAge()` method unless you assign it, like in the bottom example. Your function has nothing to do with the object. – adeneo Jan 21 '13 at 05:18

2 Answers2

0

The second example doesn't work because you haven't defined setAge, as you have here bob.setAge = setAge;. You created a new Object(), not a new custom-defined object. You're using sorta hybrid code... this is how you could do "classes"

var MyObject = function (age) {
  this.age = age;
  var that = this;
  this.setAge = function (newAge) {
    that.age = newAge;
  }
};
var foo = new MyObject(10);
alert(foo.age);
foo.setAge(20);
alert(foo.age);
Raekye
  • 5,081
  • 8
  • 49
  • 74
0

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:

function Person(){
this.age = 30;
this.setAge = function(age){
 this.age = age;
 return this;
}
}

var bob = new Person;
bob.setAge(20);
console.log(bob.age);
Ethan
  • 2,754
  • 1
  • 21
  • 34