Anonymous JavaScript objects + prototype chain. How?
Posted: Sun Apr 27, 2008 1:48 am
I can create an anonymous object like this:
[js]var obj = new (function() { this.someMethod = function someMethod() { //whatever }});[/js]
So then how come I can't do this?
[js]var obj = new (function() { this.constructor.prototype = new AnotherClass(); //INGORED});[/js]
Are there any other ways to create an anonymous subclass in JavaScript?
In pseudo I was hoping to be able to pass an anonymous instance to a method of another object:
[js]function Messenger() { var words = []; this.say = function say(word) { words.push(word); } this.getMessage = function getMessage() { return words.join(" "); }} function Receiver() { this.acceptMessageFrom = function acceptMessageFrom(messenger) { alert("Messenger says '" + messenger.getMessage() + "'"); }} //Use case (doesn't work -- prototype ignored) var receiver = new Receiver(); receiver.acceptMessageFrom(new (function() { this.constructor.prototype = new Messenger(); this.say("Hello"); this.say("World!");}));[/js]
[js]var obj = new (function() { this.someMethod = function someMethod() { //whatever }});[/js]
So then how come I can't do this?
[js]var obj = new (function() { this.constructor.prototype = new AnotherClass(); //INGORED});[/js]
Are there any other ways to create an anonymous subclass in JavaScript?
In pseudo I was hoping to be able to pass an anonymous instance to a method of another object:
[js]function Messenger() { var words = []; this.say = function say(word) { words.push(word); } this.getMessage = function getMessage() { return words.join(" "); }} function Receiver() { this.acceptMessageFrom = function acceptMessageFrom(messenger) { alert("Messenger says '" + messenger.getMessage() + "'"); }} //Use case (doesn't work -- prototype ignored) var receiver = new Receiver(); receiver.acceptMessageFrom(new (function() { this.constructor.prototype = new Messenger(); this.say("Hello"); this.say("World!");}));[/js]