Search code examples
javascriptcallapplyvariable-assignment

JavaScript call() and apply() Method and variable assignment


I am currently learning JavaScript using a book. An example explains the dual purpose of functions.

function Person(name) {
  if (this instanceof Person) {
    this.name = name
  } else {
    throw new Error("Nutze new")
  }
}
let aPerson = new Person("Astrid"); 
// let aPerson = Person("Astrid"); // throws an error
let notAPerson = Person.apply(aPerson, ["Elmar"]);
let notAPerson2 = Person.call(aPerson, "Peter");
console.log(aPerson); //  Object { name: "Peter" }
console.log(notAPerson); //  undefined
console.log(notAPerson2); //  undefined

I understand, that I can set a contex with the apply() or the call() method. But I do not understand, why the variables notAPerson and notAPerson2 are undefined?

It would be great if someone could explain this to me.


Solution

  • the new keyword changes how your function executes. When used without new, it does exactly what it says it does in the function body. But when you call the function with new, it works kind of like this:

    function Person(name) {
      var this = {}
      if (this instanceof Person) {
        this.name = name
      } else {
        throw new Error("Nutze new")
      }
      return this
    }
    

    So when you call the function with new, this is a brand new object, which gets returned automatically. When you call the function later without new, this is the aPerson object you created previously, because you're explicitly setting the context using call and apply. Also, when you don't use new, the function doesn't return anything, it only assigns to this, which is why notAPerson and notAPerson2 remain undefined.