Why does one need to call the function in an Object (constructor) in order to use a method that uses .this (JavaScript)

纵然是瞬间 提交于 2019-12-11 19:13:32

问题


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?


回答1:


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);



回答2:


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);


来源:https://stackoverflow.com/questions/14433008/why-does-one-need-to-call-the-function-in-an-object-constructor-in-order-to-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!