Object Oriented

Property

JavaScript

 

Defining Property

ECMAScript 5
function Person(name, age) {
  
  this.name = name;
  this.age = age;
  
}

Properties are like variables.

Properties keep the state of the current object.

Properties in JavaScript can be set on objects even after objects are created.

Here we are setting properties name and age as soon as the object is created.

The this keyword points to the current object in the Class (Constructor Functions) definition.

 

Defining Property (ES6)

ECMAScript 2015
class Person {
  
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
}

Properties don't necessary need to be defined in the instantiation of the object, and they can be added to the object at any point.

In JavaScript ES6 class syntax, in order to define the properties in instantiation phase, they can be written inside constructor() method.

 

Accessing Properties

ECMAScript 5
var person1 = new Person();

person1.name = 'Sarah';
theName = person1.name;   // "Sarah"

You can access properties (attributes) of an object using the . operator.

The other way to access attributes in JavaScript is by using bracket operator [].

var person1 = new Person();

person1['name'] = 'Sarah';
theName = person1['name'];   // "Sarah"
 

this

ECMAScript 5
function Person(name, age) {
  
  this.name = name;
  this.age = age;
  
  this.greet = function() {
    console.log("Hi! I'm " + this.name);
  }
  
  this.birthday = function() {
    this.age = this.age + 1;
  }
  
}

The this keyword inside Function Constructors and Classes are generally refer to the current object created from that Function Constructor or Class.

In JavaScript, Since you have control over what this can point to, using it can sometimes get tricky.

You can use this keyword followed by . operator to access properties and methods from withing the class.