Reputation: 512
I thought I understood the javascript prototype object and how to use it, but now I've run into something that has me a little stumped. When trying to run the code below mpo.testFire()
fires with no issues, but I get the error Uncaught TypeError: Object # has no method 'fireAlert' when trying to invoke mpo.fireAlert()
which I thought was part of the prototype:
<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
};
}();
If I change the code and move everything to the object's prototype like the code below everything works as expected:
$("#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
};
}();
I'm guessing there is a scope issue since in the first example I return an interface from the parent object. Can anyone explain why the first example does not work?
Upvotes: 1
Views: 123
Reputation: 19039
You're returning an object literal
return {
testFire:testFire
};
which "overrides" the result from new
(because it's an object. Returning, for example, a string literal would return the created object).
This is in ES5 spec 13.2.2.
Upvotes: 1
Reputation: 14848
You are returning an object literal from your first implementation of MyObject constructor which knows nothing of the prototype chain MyObject is part of. In the second implementation the empty constructor returns the new context that was created which is in fact a MyObject object which knows about the appropriate prototype chain
Upvotes: 2