Why does one need to call the function in an Objec

2019-08-25 08:17发布

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?

2条回答
你好瞎i
2楼-- · 2019-08-25 08:46

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);
查看更多
一夜七次
3楼-- · 2019-08-25 09:03

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);
查看更多
登录 后发表回答