如何在函數原型中正確創建函數? 什麼我是這樣的:在函數原型中爲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;}」,但我期待着李四。
你不調用'myFunc',你只是返回函數本身。如果你想調用'myFunc',那麼它應該'myFather.name()。myFunc()' – 2015-02-09 19:30:43
什麼是「函數原型」? – Bergi 2015-02-09 19:30:51
@MarcB:是的,[雖然即使這樣也行不通](https://stackoverflow.com/questions/16502467/prototype-deep-scope-of-this-to-access-instances-scope) – Bergi 2015-02-09 19:31:38