Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript The use of "this"

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #149919
    magician11
    Participant

    I’m going through some lessons at codecademy.com

    function add(firstName, lastName, email, phoneNumber) {
        contacts[contacts.length] = {
            this.firstName: firstName,
            this.lastName: lastName,
            this.email: email,
            this.phoneNumber: phoneNumber
        };
    }
    

    For this code.. why exactly is “this” not required?

    versus for a constructor..

    function Human(name, age) {
    
    this.name = name;
    this.age = age;
    }
    
    #150019
    whatsoever
    Participant

    When you use a constructor function, you invoke it with the ‘new’ operator:

    function Person (firstName, lastName) { 
    
    
    this.firstName = firstName; 
    this.lastName = lastName; 
    }
    
    var johnSmith = new Person('John', 'Smith'); 
    

    Which puts the ‘johnSmith’ object in the context of ‘this’ in the constructor function.

    The ‘add’ function takes several parameters, adds a new object to the contacts array and sets the properties of the object using object literal notation which does not require ‘this’ when setting properties.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.