Xander Juneau
Xander Juneau

Reputation: 25

Are we declaring a function as a method on a variable?

I have been learning JS on my own and completed an 8 hour course on the basics. Now I am following another course where the lecturer, as it seems to me, is creating a function using dot notation. I am not sure if this is what is happening and I am having a hard time understanding exactly what it is doing.

function Person(fName, lName) {
    this.firstName = fName
    this.lastName = lName
}
const person1 =  new Person("Bruce", "Wayne")
const person2 =  new Person("Bat", "Man")

person1.getFullName = function () {
    return this.firstName + ' ' + this.lastName
}

console.log(person1.getFullName())

The part I am confused about is:

person1.getFullName = function () {
    return this.firstName + ' ' + this.lastName

}

I see in the Person() function we are creating an object called person1 using "this" and a key to pass in parameters as values for those keys. However it looks to me like there is a function being assigned to the person1 object and what I am assuming is the name of the function, looks like a method on the person1 object using dot notation. Can anyone explain how this works?

Upvotes: 0

Views: 45

Answers (3)

wally
wally

Reputation: 68

function Person(fName, lName) {
    this.firstName = fName
    this.lastName = lName
}
const person1 =  new Person("Bruce", "Wayne")
const person2 =  new Person("Bat", "Man")
 
person1.getFullName = function () {
    return this.firstName + ' ' + this.lastName
}

console.log(person1.getFullName())

Basically a new property called getFullName is created for the object person1. This new property is defined to return the first name and the lastname of the person1 object. So when you call console.log(person1.getFullName()) this will print the firstname and the lastname of the person1.

Upvotes: 0

Quentin
Quentin

Reputation: 943537

Objects have properties.

Properties have values.

Functions are a value.

If the value of a property is a function then we call that a method.

That's all there is to it.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816404

The line

person1.getFullName = ...

is a normal assignment statement. It assigns the value on the right hand side to the property getFullName of the object in person1. If the property doesn't exist yet it will be created.

Functions are values (objects) like any other in JavaScript and thus they can be used everywhere were a value is expected.

So yes, person1.getFullName will contain a function and it can be called like any other function: person1.getFullName().

Upvotes: 3

Related Questions