Object Oriented

Method

JavaScript

 

Defining Method

ECMAScript 5
function Person() {
  // ...
}

Person.prototype.greet = function() {
  console.log('Hi!');
}

Class Methods can be defined in the same way as properties in JavaScript.

function Person() {
  
  // ...
  
  this.greet = function() {
    console.log('Hi!');
  }
  
}

But in practice methods are being defined on the prototype objects. This is because of the way JavaScript works.

To learn more about prototypes, check out Inheritance section.

Remember that you can always use ES6 arrow functions when they are available:

Person.prototype.greet = () => {
  console.log('Hi!');
}

To learn more about ES6 arrow functions, checkout Function topic.

 

Defining Method (ES6)

ECMAScript 2015
class Person {
  
  // ...
  
  greet() {
    console.log('Hi!');
  }
  
}

This is an ES6 defining a method.

The method greet is going to be defined on the prototype of the function constructor Person (a.k.a. Class) just like we had defined it before.

We try to provide samples in older ES5, since this way of defining Classes and methods (ES6) are exactly going to be interpreted to Function Constructors.

 

Method Parameters

ECMAScript 5
function Person() {
  // ...
}

Person.prototype.getName = function() {
  return this.name;
}

Person.prototype.setName = function(name) {
  this.name = name;
}

Person.prototype.sleep = function(from, duration) {
  var output = this.name + ' slept from ' +
    from + ' for ' + duration + ' hours.';
  console.log(output);
}

Parameters are inputs to methods.

Parameters are separated by comma (,).

Parameters are not associated with types on declaration.

Parameters of type object (also arrays, functions) are passed by reference.

Parameters of other types are passed by value.

 

Invoking Methods

ECMAScript 5
var person1 = new Person();

person1.setName('Sam');
var name = person1.getName(); // Sam
person1.sleep(10, 7); // Sam slept from 10 for 7 hours.

The most common way of invoking methods on an object is using the parantheses ().

Other ways are, using call and apply methods, which are used in special cases:

person1.setName.call(person1, 'Sam');
person1.setName.apply(person1, ['Sam']);

To learn more about call and apply, check out the Function topic.

 

Invoking Methods from inside Class

ECMAScript 5
function Person() {
  // ...
  
  this.getAge = this.getAge.bind(this);
  this.setAge = this.setAge.bind(this);
  this.birthday = this.birthday.bind(this);
}

Person.prototype.getAge = function() {  
  return this.age;
}

Person.prototype.setAge = function(age) {  
  this.age = age;
}

Person.prototype.birthday = function() {  
  this.setAge(this.getAge() + 1);
}

Methods can be accessed from inside a class explicitly by calling it on this.

Because of the way JavaScript contexts work, this can get tricky sometimes. In order to not face those issues, we should bind this to all class methods in the constructor.