Reputation: 63
Is there a way to expose an objects' prototypes through another object?
var foo = function () {
var foo = {
bar: bar,
boo: boo
}
return foo;
function bar (age) {
this.age = age;
}
bar.prototype.shoutAge = function () {
alert('My age is ' + this.age);
}
function boo (age) {
this.age = age;
boo.prototype.shoutAge = function () {
alert('My age is ' + this.age);
}
}
}
var foo = foo();
var far = new foo.bar(13); // bar {age: 13}
far.shoutAge(); // far.shoutAge is not a function
var far = new foo.boo(13); // boo {age: 13} with __proto__
far.shoutAge(); // alert('My age is 13');
In this code, the 'bar' object is set up with prototype inheritance--but exposing bar loses the inheritance of 'shoutAge'.
However, the 'boo' object has the prototype declared inside of it and the outside function has access to the method 'shoutAge'.
I don't think that the latter is a best practice even though it functions. So what would the best practice here be?
I don't want each instance of 'bar' to have it's own 'shoutAge' method, especially if there are potentially hundreds of instances of 'bar'. Would you typically just create a separate object for 'bar' instead of exposing it through 'foo'?
Upvotes: 6
Views: 163
Reputation: 55678
Looks like this is just an order-of-operations issue:
var Foo = function () {
function bar (age) {
this.age = age;
}
bar.prototype.shoutAge = function () {
alert('My age is ' + this.age);
}
var foo = {
bar: bar,
boo: boo
}
return foo;
}
I think this is because the bar.prototype
assignment is never executed in your code. The bar
function definition gets hoisted, so it's available in the object you return, but the prototype assignment is an additional statement after the return
statement, and the control flow never reaches it. Simply moving the return
to the end fixes the issue.
Upvotes: 3