1

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.

3
  • 3
    Because your constructor function doesn't return a value. It just modifies the this object. Commented Mar 7, 2019 at 20:21
  • 2
    I'd like to mark this as a typo but I'm not sure I should. Really, you are asking why a function doesNotReturnAnything() { console.log("this is the entire body") } when invoked does not produce a value. Commented Mar 7, 2019 at 20:27
  • Many Thanks. Now it is clear to me. Commented Mar 7, 2019 at 20:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad I could clear things up for you. Please select this answer as 'correct' if you feel that it answers your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.