【问题标题】:calling javascript method to change object property调用javascript方法更改对象属性
【发布时间】:2016-04-13 04:40:55
【问题描述】:

我正在尝试在下面的代码中调用 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

【问题讨论】:

    标签: javascript function object properties


    【解决方案1】:

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

    setAge.call( bob, 50 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多