本文介绍了为什么要使用使用.this(JavaScript)的方法,需要在对象(构造函数)中调用该函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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);
在编译器中返回"bob.setAge()不是函数"吗?
it returns "bob.setAge() is not a function" in the compiler?
推荐答案
您已经创建了一个对象'Bob',但是在分配该对象之前,该对象没有方法'setAge'.
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);
这篇关于为什么要使用使用.this(JavaScript)的方法,需要在对象(构造函数)中调用该函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!