Skip to content

Instantly share code, notes, and snippets.

@shahbazsyed
Created April 25, 2017 08:28
Show Gist options
  • Save shahbazsyed/88f66e35cd1ef89e2f424af3e9073bc3 to your computer and use it in GitHub Desktop.
Save shahbazsyed/88f66e35cd1ef89e2f424af3e9073bc3 to your computer and use it in GitHub Desktop.
Basic OOP in Js
var x = new Object(); // empty object in js
var y= {} ; // another way of creating empty object
// Adding properties to our empty object
y.name="Tim";
y.age=20;
y.getName= function(){
return this.name;
};
console.log(y);
console.log(y.getName());
// delete operator can be used to remove a property from the object
delete(y.age);
console.log(y);
// To view the constructor of an object
console.log(y.constructor);
// Adding private variables
var Pizza = function(){
var crust='thin'; //private property
var toppings=3;
this.hasBacon = true;
this.getCrust = function(){
return crust; // Private variables are available to every object,hence there is no need to use this to access it
};
// private method
var getToppings= function(){
return toppings;
};
var temp = {};
temp.getToppings= getToppings;
return temp;
};
var pizzaA = new Pizza();
console.dir(pizzaA); // crust is not visible(private), but hasBacon is visible(public)
console.log(pizzaA.getCrust()); // thin
console.log(pizzaA.getToppings()); // Won't work without returning the temp object.
// temp works because of Closures!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment