JavaScript プロトタイプ オブジェクトとその使用方法は理解できたと思っていましたが、ちょっと困ったことに遭遇してしまいました。以下のコードを実行しようとするとmpo.testFire()
問題は発生しませんが、エラー Uncaught TypeError: Object # has no method 'fireAlert' が発生しmpo.fireAlert()
ます。
<body>
<a href="#" id="testBtn">Click Me</a>
</body>
// Click handler, create new object
// call parent method and prototype method
$("#testBtn").click(function(e) {
e.preventDefault();
var mpo = new Myobject();
mpo.testFire();
mpo.fireAlert();
});
Myobject = function () {
var testFire = function () {
alert('testFire');
};
return {
testFire:testFire
};
};
Myobject.prototype = function() {
var fireAlert = function() {
alert('made it to fireAlert');
};
return {
fireAlert:fireAlert
};
}();
コードを変更して、以下のコードのようにすべてをオブジェクトのプロトタイプに移動すると、すべてが期待どおりに機能します。
$("#testBtn").click(function(e) {
e.preventDefault();
var mpo = new Myobject();
mpo.testFire();
mpo.fireAlert();
});
Myobject = function () {
// constructor logic here maybe?
};
Myobject.prototype = function() {
var fireAlert = function() {
alert('made it to fireAlert');
};
var testFire = function () {
alert('testFire');
};
return {
fireAlert:fireAlert,
testFire:testFire
};
}();
最初の例では親オブジェクトからインターフェイスを返すため、スコープの問題があると推測しています。最初の例が機能しない理由を説明できる人はいますか?