alankis

app.js

Oct 26th, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // class product
  2. Product = function(product) {
  3.       // instantiation works fine
  4.     var id = Object.getPrototypeOf(this).id++;
  5.     this.id = function() {
  6.         return id;
  7.       };
  8.      
  9.     var title = product.title;
  10.     this.title = function(productTitle) {
  11.         if(productTitle !== undefined) title = productTitle;
  12.             return title;
  13.        
  14.     };
  15.     var price = product.price;
  16.    
  17.     this.price = function(productPrice) {
  18.         if(productPrice !== undefined) price = productPrice;
  19.                
  20.        
  21.             price = price.toString();
  22.             // returns $ on single and chain call
  23.             return "$" + price.substr(0, price.length-2).concat('.', price.substr(-2));
  24.            
  25.        
  26.    
  27.         };
  28.    
  29.     this.formatted_price = function() {
  30.         return "$" + this.price(); // concat also works fine
  31.     };
  32.    
  33.     this.discount = function() {
  34.          // set price -1$ (100)
  35.          price -= 100;
  36.        
  37.          // return my obj here
  38.          return this;
  39.        
  40.     };
  41.    
  42.  
  43. };
  44.  
  45. // static member - shared between object constructor and inherited in instances
  46. Product.prototype.id = 0;
  47.  
  48. // nethod on class = static method
  49.  
  50. Product.unique_id = function() {
  51.     return Product.prototype.id++;
  52. };
  53.  
  54.  
  55.  
  56. // class SubProduct
  57. SubProduct.prototype = new Product();
  58. /*
  59. SubProduct.prototype.unique_id = function() {
  60.     return "sub_" + Product.prototype.id++;
  61. };
  62. */
  63.  
  64.  
  65.  
  66.  
  67. /* Simple test methods both on instance and static */
  68. /*
  69. console.log("Call 1: " + Product.unique_id() + "// 0");
  70. console.log("Call 2: " + Product.unique_id() + "// 1");
  71. console.log("Call 3: " + Product.unique_id() + "// 2");
  72.  
  73.  
  74. console.log(p1.id());
  75.  
  76. console.log("Call 4: " + Product.unique_id() + "// 4");
  77. */
  78.  
  79.  var p1 = new Product({
  80.     title: 'Keyboard',
  81.     price: 10050
  82. });
  83. p1.id();
  84.  
  85. p1.id();                    // 1
  86. p1.title();                 // 'Keyboard'
  87. p1.title('Cool keyboard');  // 'Cool keyboard'
  88. p1.title();                 // 'Cool keyboard'
  89.  
  90. p1.price(); // returns $ here too, which is BAD
  91. p1.price(10050);
  92. p1.formatted_price();
  93. p1.discount().price();
  94.  
  95. var p2 = new SubProduct({
  96.     title: 'Monitor',
  97.     price: 500000
  98.   });                        
  99.  
  100. p2.unique_id();
Advertisement
Add Comment
Please, Sign In to add comment