Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // class product
- function Product(product) {
- // instantiation works fine
- var id = Object.getPrototypeOf(this).id++;
- this.id = function() {
- return id;
- };
- var title = product.title;
- this.title = function(productTitle) {
- if(productTitle !== undefined) title = productTitle;
- return title;
- };
- var price = product.price;
- this.price = function(productPrice) {
- if(productPrice !== undefined) price = productPrice;
- price = price.toString();
- // returns $ on single and chain call
- return "$" + price.substr(0, price.length-2).concat('.', price.substr(-2));
- };
- this.formatted_price = function() {
- return "$" + this.price(); // concat also works fine
- };
- this.discount = function() {
- // set price -1$ (100)
- price -= 100;
- // return my obj here
- return this;
- };
- }
- // static member - shared between object constructor and inherited in instances
- Product.prototype.id = 0;
- // nethod on class = static method
- Product.unique_id = function() {
- return Product.prototype.id++;
- };
- // class SubProduct
- // define constructor
- function SubProduct(subproduct) {
- var id = Object.getPrototypeOf(this).id++;
- var title = subproduct.title;
- var price = subproduct.price;
- }
- SubProduct.prototype = new Product();
- /*
- SubProduct.prototype.unique_id = function() {
- return "sub_" + Product.prototype.id++;
- };
- */
- /* Simple test methods both on instance and static */
- /*
- console.log("Call 1: " + Product.unique_id() + "// 0");
- console.log("Call 2: " + Product.unique_id() + "// 1");
- console.log("Call 3: " + Product.unique_id() + "// 2");
- console.log(p1.id());
- console.log("Call 4: " + Product.unique_id() + "// 4");
- */
- var p1 = new Product({
- title: 'Keyboard',
- price: 10050
- });
- p1.id();
- p1.id(); // 1
- p1.title(); // 'Keyboard'
- p1.title('Cool keyboard'); // 'Cool keyboard'
- p1.title(); // 'Cool keyboard'
- p1.price(); // returns $ here too, which is BAD
- p1.price(10050);
- p1.formatted_price();
- p1.discount().price();
- var p2 = new SubProduct();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement