OOP in JavaScript

var Circle = { // Class
	area: function() {
		return this.radius * this.radius * Math.PI;
	}
}
 
var instance = { radius:5 };
instance.__proto__ = Circle; // inheritance via prototype, does not work in IE
 
console.log( instance.area() ); // prints '78.5398'
function Circle(radius) { // Class
	this.radius = radius;
}
Circle.prototype.area = function() {
	return this.radius * this.radius * Math.PI;
}
var instance = new Circle(5);
console.log( instance.area() ); // prints '78.5398'

Data and access properties

var createPerson = function(firstName, lastName) {
  var person = {};
 
  Object.defineProperties(person, {
    firstName : {
      value : firstName,
      writable : true
    },
    lastName : {
      value : lastName,
      writable : false
    },
    fullName : {
      get : function() { 
        return this.firstName + ' ' + this.lastName; 
      },
      set : function(value) { 
        this.firstName = value + ' set ';
        this.lastName = value + ' set ';
      }
    }
  });
 
/*  Object.defineProperty(person, "firstName", {
    value : firstName,
    writable : true
  });
 
  Object.defineProperty(person, "lastName", {
    value : lastName,
    writable : false
  });
*/
 
  return person;
};
 
var person = createPerson("John", "Doe");
//person.firstName = 'Jane'; // sets firstName to 'Jane'
//person.lastName = 'New'; // cannot set lastName
//person.fullName = 'New'

Leave a Reply

Your email address will not be published. Required fields are marked *