【问题标题】:javascript prototype method returns a string valuejavascript原型方法返回一个字符串值
【发布时间】:2016-09-04 05:41:58
【问题描述】:

在学习对象原型的过程中,我遇到了下面的例子。

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Person.prototype.name = function() {
  return this.firstName + " " + this.lastName
};

var myFather = new Person("John", "Doe", 50, "blue");
alert(myFather.name);

当我尝试使用 html 页面通过浏览器运行时,弹出以下警告消息。

function() {
  return this.firstName + " " + this.lastName
}

因此,它不是返回“John Doe”,而是将整个函数作为字符串返回。 如何解决?

PS:我使用 VS Code,我使用 node.js live-server 在浏览器中运行。

【问题讨论】:

  • alert(myFather.name());

标签: javascript object prototype


【解决方案1】:

需要通过这种方式执行函数myFather.name()

var myFather = new Person("John", "Doe", 50, "blue");
alert(myFather.name());

JSFIDDLE

【讨论】:

    【解决方案2】:

    你必须调用函数

    alert(myFather.name());
    

    【讨论】:

      【解决方案3】:

      你需要使用()调用函数

      myFather.name()
      

      function Person(first, last, age, eye) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
        this.eyeColor = eye;
      }
      
      Person.prototype.name = function() {
        return this.firstName + " " + this.lastName
      };
      
      var myFather = new Person("John", "Doe", 50, "blue");
      console.log(myFather.name());

      【讨论】:

        【解决方案4】:

        这是您正在使用的功能。你能像alert(myFather.name());一样使用它吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-14
          • 2012-12-14
          • 2016-10-27
          • 2012-07-04
          • 2013-03-31
          相关资源
          最近更新 更多