2015-02-09 91 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