My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

What are JavaScript Methods and Why are we borrowing them?

Purva Sharma's photo
Purva Sharma
·May 11, 2022·

4 min read

What are JavaScript methods?

Before borrowing a method let us revise what is a javascript method?

Any function written inside an object as a property is a JavaScript method.

const countryCapital = {
// Property  //value
country   :  "India",
capital :    "Delhi",
getCapital:  function(){ return this.Capital }
}
// Here getCapital() is a javascript method that can 
// be accessed using (.) dot notation.
let capitalOfIndia = CountryCapital.getCapital()
console.log(capitalOfIndia)
//Output : Delhi

What is method borrowing?

Method borrowing is used when you already have a method defined for an object, and you want to be able to use it with a similar object that doesn't have that method defined.

Role of this in function borrowing?

this in javascript basically refers to an object during a function/method invocation, In Method Invocation this refers to the object that owns the 'Method'.

Note: arrow functions can not be defined as an object method as they always represent the object that defined the arrow function.

const thisFunc = {
  name:"TKS",
  age:20,
  getAge : function(){
    return this.age
  }
}
console.log(thisFunc.getAge())
// Output: 20

// Here getAge() is a method inside an object and 'this'
// here will point/refer to 'age' inside the 'thisFunc'.

const newObj = {
  name:"KS",
  age:21
}
console.log(newObj.getAge())
// Output: TypeError: newObj.getAge() is not a function.
// The error here can also mean that the object you are calling the 
// method on does not have this method.

Note: Each type of invocation creates its own context thus this refers differently to different invocation types.

So to use a method of an object with a similar kind of object without redefining it we use function borrowing methods which help in referring/pointing 'this' to the object we want to call the function on and get the desired output.

How can we borrow a method in JavaScript?

With inbuilt methods like call(), apply(), and bind() we can borrow a method/function from an object and call it with another object.

Lets look closer into call(), apply(), bind()

Call()

The call() method invokes a function with a given this value (which is an object) while the arguments are provided to it individually. call() takes two arguments.

call(obj to call the borrowed method on, extra arguments(if any))
Syntax:  obj1.objMethod.call(obj2,arg1,arg2......)
// obj1 : object where method is defined
// objMethod: method to be borrwed
// obj2 : object where borrowed method will be called
// arg1,arg2: arguments defined separately

Ex. lets call the getCapital() of ex.1 using call to an another object.

const countryCapitalTwo = {
// Property  //value
Country   :  "South Korea",
Capital :    "Seoul",
}
let c = countryCapital.getCapital.call(countryCapitalTwo)
console.log(c)
//Seoul

apply()

The apply() method invokes a function with a given this value (which is an object), while the arguments args are provided to it as an array.

apply(obj to call the borrowed function on, [extra arguments(if any)])
Syntax:  obj1.objMethod.apply(obj2,[arg1,arg2......])

// obj1 : object where method is defined
// objMethod: method to be borrwed
// obj2 : object where borrowed method will be called
// [arg1,arg2...]: array of arguments
const movie = {
  name:"the werewolf boy",
  getYearNlang: function(year,lang){return this.name + " " + year + " " + lang }
}

const movieTwo={
  name: "SnowBall",
}

// console.log(movie.getYearNlang(2013,"korean"))
//Output : the werewolf boy 2013 korean
console.log(movie.getYearNlang.apply(movieTwo,[2015,"english"]))
//Output: SnowBall 2015 english

The only difference between call() and apply() method is that in apply() we pass arguments as an array.

bind()

The bind() method "binds" the borrowed method with the object and returns a copy of that method to use later. bind() helps in preserving the value of 'this' as the values of 'this' is likely to be lost in a callback function. unlike apply() and call(), it doesn't invoke immediately rather it binds the method with specific 'this' values which can be called/invoked later.

let bindMethod = obj1.objMethod(obj2)
// here bindMethod will hold the returned value from objMethod with 
// reference to obj2 which can be used later on.

// to invoke the method
bindMethod()
const movie = {
  name:"the werewolf boy",
  getYearNlang: function(year,lang){return this.name + " " + year + " " + lang }
}

const movieTwo={
  name: "SnowBall",
}

let movieBind = movie.getYearNLang.bind(movieTwo,2015,"english")
console.log(movieBind())

That's all for my understanding of the topic. Do comment your thoughts. Thank you 😄