2015-02-09 84 views
1

如何在函数原型中正确创建函数? 什么我是这样的:在函数原型中为Javascript创建函数

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

当我运行这个它返回“我的父亲是函数(){this.firstName +”“+ this.lastName;}”,但我期待着李四。

+1

你不调用'myFunc',你只是返回函数本身。如果你想调用'myFunc',那么它应该'myFather.name()。myFunc()' – 2015-02-09 19:30:43

+0

什么是“函数原型”? – Bergi 2015-02-09 19:30:51

+0

@MarcB:是的,[虽然即使这样也行不通](https://stackoverflow.com/questions/16502467/prototype-deep-scope-of-this-to-access-instances-scope) – Bergi 2015-02-09 19:31:38

回答

4

您需要呼叫功能,请将()添加到myFunc。在你的例子中,你添加了对内部函数的引用。

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

另外加returnmyFunc。为了从父作用域属性 - 保存参考this

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

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

Example

+0

更好,谢谢。 – Bergi 2015-02-09 19:41:01

+0

此解决方案有效,谢谢!我想我的这个用法在这个问题上是不正确的。 – BlueElixir 2015-02-09 19:44:56

0

MYFUNC是一个函数。当你给它打电话时,请拨打电话myfunc()

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(); 
+0

更清洁:https://stackoverflow.com/questions/17474390/defining-a-javascript-prototype – Bergi 2015-02-09 19:42:00