Home > database >  Function shown as prototype in Javascript
Function shown as prototype in Javascript

Time:08-17

So as you can see I have a greeting function and similar to that the getsMarried function. However, getsMarried is shown as a prototype (colored green in VSCode, opposed to yellow). Is this because I use this.lastName? Because the tutorial I am learning from is also doing the same without it shown as a prototype.

const personPrototypes = {
  greeting: function(){
    `$Hello there ${this.firstName} ${this.lastName}`
  },
  getsMarried: function(newLastName){
    this.lastName = newLastName
  }
}

const mary = Object.create(personPrototypes)
mary.firstName = 'Mary'
mary.lastName = 'Williams'
mary.age = 30

mary.getsMarried('Wlii')

console.log(mary.greeting())

CodePudding user response:

console.log does not show result as there is nothing to show. So we can return your greeting from the function to be shown in console.log.

As mdn says:

The return statement ends function execution and specifies a value to be returned to the function caller.

An example:

const personPrototypes = {
  greeting: function(){
    return `$Hello there ${this.firstName} ${this.lastName}`
  },
  getsMarried: function(newLastName){
    this.lastName = newLastName
  }
}

const mary = Object.create(personPrototypes)
mary.firstName = 'Mary'
mary.lastName = 'Williams'
mary.age = 30

mary.getsMarried('Wlii')

console.log(mary.greeting())

  • Related