What is wrong with constructor Function, Why can't I use get function with constructor while it's working with literal?

What is wrong with constructor Function, Why can’t I use get function with constructor?

function Person(name,surname,dob){

this.name:name,

this.surname=surname,

this.fullname=undefined,

this.dob=dob,

get getName(){

return this.name

}

}

const person={

name="Person",

get getName(){

return this.name

}

}

Hey @erdldncr,
It looks like on line 3 of your code, you used : instead of the =

You also don’t need the commas, after every declaration, since it’s a function.

Now to answer your question, getters in JavaScript only works with ES2015 Classes and object literals. So if you really want to use the get keyword, you have to use classes. But there are other ways to do this. Here’s how to solve this

1st solution: Turn the getter into a function that directs to this

function Person(name,surname,dob){
  // CODE HERE

    this.getname = function () {
        return this.name
    }
}

let x = new Person('Jo', 'J', '25')

// Now you have to call it like a function
console.log(x.getname())

2nd solution: Use ES2015 classes

class Person {
    constructor (firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    // Now JS won't scream at you
    get getFullName() {
        return this.firstName + this.lastName;
    }
}

let x = new Person('Hello', 'World');

// By using getters, you don't have to call it like a function
console.log(x.getFullName)

Hope this helps!

1 Like

Yeah, I got it, so I have to make a class , right? It means “get” key work does not work with constructor functions as it works with literal object. In order to use get with constructor, I have to make a class. Am I Right?

1 Like

Yup, JavaScript getters only works in an object literals and ES6/ES2015 classes. So if you really want to use a getter, you have to make a class constructor.

1 Like

It doesn’t work in a constructor full stop, regardless of whether that constructor is a standalone function (like you have there), or the constructor function using class syntax. It needs to be defined on the prototype, doesn’t matter if that is using class syntax or not (just with class, it’s automatically going to be defined there, you don’t need to write boilerplate Object.defineProperty stuff). eg:

function Person (name, surname, dob) {
  this.name = name;
  this.surname = surname;
  this.dob = dob;
}

Object.defineProperty(Person.prototype, "fullName", {
  get: function () {
    return `${this.name} ${this.surname}`
  }
});

So

dan = new Person("Dan", "Couper", "00/00/0000")
console.log(dan.fullName) // logs "Dan Couper"
1 Like