【问题标题】:Binding and calling a method on a JS instance在 JS 实例上绑定和调用方法
【发布时间】:2016-12-20 17:09:45
【问题描述】:

我有这个:

function Person(number){
  this.number = number;
}

Person.prototype.wording = function(){
  if (this.person == 1){
    return "person is";
  } else {
    return "people are";
  }
};

var per1 = new Person(1);
console.log(per1.wording, '**');

我退出了[Function] 当我在我的实例上调用它时,如何将方法绑定到对象或告诉它运行该函数

【问题讨论】:

  • wording 是一个函数,只需使用per1.wording() 调用它。另外,请记住this.person 将始终为undefined(至少使用当前代码),也许您的意思是this.number?
  • 哦。我可能误解了 is/are。新人(5);//对我来说毫无意义
  • @haim770 这对我来说很特别:/。谢谢!

标签: javascript object methods


【解决方案1】:

正如haim770所指出的,您需要通过添加括号来调用per1.wording:per1.wording()。

另外,您可能指的是this.number,而不是this.person。

function Person(number){
  this.number = number;
}

Person.prototype.wording = function(){
  
  //changed this.person to this.number
  if (this.number == 1){ 
    return "person is";
  } else {
    return "people are";
  }
};

var per1 = new Person(1);

// invoked wording by adding ()
console.log(per1.wording(), '**'); 

【讨论】:

    【解决方案2】:
    console.log(per1.wording());
    

    这应该可以解决它。 我对您的代码的解释,以及如果我错了我会如何写这样的东西来纠正我:

    var persons=[];
    function person(name){
    persons.push(this);
    person.name=name;
    }
    function saypers(){
    if(persons.length>1){
    alert("Plural!");
    }else{
    alert("Singular!");
    }
    }
    

    做某事:

    albert=new person("albert");
    saypers();//singular
    einstein=new person("einstein");
    saypers();//plural
    console.log(persons);//albert, einstein
    

    【讨论】:

      猜你喜欢
      • 2012-11-02
      • 2018-12-12
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 2016-08-30
      • 1970-01-01
      相关资源
      最近更新 更多