调用javascript方法来改变对象属性

时间:2016-04-13 04:40:55

标签: 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 we just use the method we already made
bob.setAge = setAge;

// change bob's age to 50 here using the setAge function

1 个答案:

答案 0 :(得分:0)

由于setAge不在bob的原型链上,您必须使用callapply来调用功能并指定您希望bob成为thisArg

setAge.call( bob, 50 );