调用javascript方法更改对象属性
我试图在下面的代码中调用setAge函数,将bob的年龄更改为50岁。。。但我不知道怎么做调用javascript方法更改对象属性,javascript,function,object,properties,Javascript,Function,Object,Properties,我试图在下面的代码中调用setAge函数,将bob的年龄更改为50岁。。。但我不知道怎么做 // here we define our method using "this", before we even introduce bob var setAge = function (newAge) { this.age = newAge; }; // now we make bob var bob = new Object(); bob.age = 30; // and down here w
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge;
// change bob's age to 50 here using the setAge function
由于
setAge
不在bob
的原型链上,因此必须使用或调用该函数,并指定希望bob
成为thisArg
:
setAge.call( bob, 50 );