【问题标题】:Why does one need to call the function in an Object (constructor) in order to use a method that uses .this (JavaScript)为什么需要调用对象(构造函数)中的函数才能使用使用.this(JavaScript)的方法
【发布时间】:2013-01-04 04:12:29
【问题描述】:
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);

这可行,但是当我尝试这样做时

var setAge = function (newAge) {
  this.age = newAge;
};
var bob = new Object();
bob.age = 30;
bob.setAge(50);
console.log(bob.age);

它在编译器中返回“bob.setAge() 不是函数”?

【问题讨论】:

  • bob 是一个new Object,它没有神奇的setAge() 方法,除非你指定它,就像在底部的例子中一样。您的函数与对象无关。

标签: javascript object methods


【解决方案1】:

第二个示例不起作用,因为您还没有定义 setAge,就像您在这里 bob.setAge = setAge; 一样。您创建了一个new Object(),而不是一个新的自定义对象。你正在使用某种混合代码......这就是你可以做“类”的方式

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】:

    您创建了一个对象“Bob”,但该对象在分配之前没有方法“setAge”。

    您可能想考虑在您的设计中做这样的事情:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多