Advertisement
Guest User

JavaScript inheritance

a guest
May 14th, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function TXInstance(settings) {
  2.   this.transmit = function(data) {
  3.     // Transmit data using settings
  4.   }
  5. }
  6.  
  7. function RXInstance(settings) {
  8.   this.receive = function(data) {
  9.     // Receive data using settings
  10.   }
  11. }
  12.  
  13.  
  14. function Device(settings) {
  15.   this.settings = settings;
  16. }
  17.  
  18. Device.prototype.asTransmitter = function() {
  19.   this._txInstance = new TXInstance(this.settings);
  20.   this.transmit = function(data) {
  21.     this._txInstance.transmit(data);
  22.   }
  23.   return this;
  24. }
  25.  
  26. Device.prototype.asReceiver = function() {
  27.   this._rxInstance = new RXInstance(this.settings);
  28.   this.receive = function(data) {
  29.     this._rxInstance.receive();
  30.   }
  31.   return this;
  32. }
  33.  
  34. Device.prototype.asTransceiver = function() {
  35.   this.asTransmitter(this);
  36.   this.asReceiver(this);
  37.   return this;
  38. }
  39.  
  40. var d = new Device({foo: 'bar'});
  41. console.log(d);
  42. var tx = new Device({foo: 'bar'}).asTransmitter();
  43. console.log(tx);
  44. var rx = new Device({foo: 'bar'}).asReceiver();
  45. console.log(rx);
  46. var txrx = new Device({foo: 'bar'}).asTransceiver();
  47. console.log(txrx);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement