Lay out prototypes in an object

Is there a way to open prototype objects 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 configured with prototype inheritance, but the exposing bar loses the "shoutAge" inheritance.

However, the 'boo' object has a prototype declared inside it, and the external function has access to the 'shoutAge' method.

I don't think the latter is best practice, even if it works. So what would be the best practice here?

I do not want each instance of bar to have its own shoutAge method, especially if there are potentially hundreds of instances of bar. Did you usually just create a separate object for the bar instead of exposing it to foo?

+5
source share
1 answer

It seems like this is just an operation order problem:

 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 purpose of bar.prototype never executed in your code. The definition of the bar function gets hoisted , so it is available in the returned object, but the purpose of the prototype is an optional expression after return and the control flow never achieves this. Just moving return to the end fixes the problem.

+3
source

All Articles