在Javascript的函数原型中创建函数

时间:2015-02-09 19:29:01

标签: javascript function prototype

如何在函数原型中正确创建函数? 我有这个:

    <body>
    <p id="demo"></p><script>
function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
person.prototype.name = function() {
    return {
        myFunc: function() {
          this.firstName + " " + this.lastName;
       }
      }
};

var myFather = new person("John", "Doe", 50, "blue");

document.getElementById("demo").innerHTML =
"My father is " + myFather.name().myFunc; 
</script>

</body>

当我运行它时它返回&#34;我的父亲是函数(){this.firstName +&#34; &#34; + this.lastName; }&#34; ,但我期待John Doe。

3 个答案:

答案 0 :(得分:4)

您需要通话功能,将()添加到myFunc。在您的示例中,您添加了对内部函数的引用。

document.getElementById("demo").innerHTML = "My father is " + myFather.name().myFunc(); 

同时将return添加到myFunc。从父作用域获取属性 - 保存对this

的引用
person.prototype.name = function () {
  var _this = this;

  return {
    myFunc: function () {
      return _this.firstName + " " + _this.lastName;
    }
  }
};

Example

答案 1 :(得分:0)

Myfunc是一个功能。当您拨打电话时,请拨打myfunc()

答案 2 :(得分:0)

您不是在调用myFunc,而且该函数也不会返回任何内容。我发现这个更清洁,更好的方法来定义功能原型:

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

请注意,name现在返回return this.firstName + " " + this.lastName;

然后简单地说:

document.getElementById("demo").innerHTML = "My father is " + myFather.name();