Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. var x = new Object(); // empty object in js
  2. var y= {} ; // another way of creating empty object
  3.  
  4. // Adding properties to our empty object
  5. y.name="Tim";
  6. y.age=20;
  7. y.getName= function(){
  8. return this.name;
  9. };
  10.  
  11. console.log(y);
  12. console.log(y.getName());
  13.  
  14. // delete operator can be used to remove a property from the object
  15. delete(y.age);
  16.  
  17. console.log(y);
  18. // To view the constructor of an object
  19. console.log(y.constructor);
  20.  
  21. // Adding private variables
  22. var Pizza = function(){
  23. var crust='thin'; //private property
  24. var toppings=3;
  25. this.hasBacon = true;
  26. this.getCrust = function(){
  27. return crust; // Private variables are available to every object,hence there is no need to use this to access it
  28. };
  29.  
  30. // private method
  31. var getToppings= function(){
  32. return toppings;
  33. };
  34. var temp = {};
  35. temp.getToppings= getToppings;
  36.  
  37. return temp;
  38. };
  39. var pizzaA = new Pizza();
  40.  
  41. console.dir(pizzaA); // crust is not visible(private), but hasBacon is visible(public)
  42. console.log(pizzaA.getCrust()); // thin
  43. console.log(pizzaA.getToppings()); // Won't work without returning the temp object.
  44. // temp works because of Closures!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement