Last edited 2 years ago
by Horst Schreiber

Object-oriented Programming with JavaScript

Revision as of 11:14, 3 December 2021 by Horst Schreiber (talk | contribs) (Created page with "==Object basics== As with many things in JavaScript, creating an object often begins with defining and initializing a variable. Try entering the following line below the JavaS...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Object basics

As with many things in JavaScript, creating an object often begins with defining and initializing a variable. Try entering the following line below the JavaScript code that's already in your file, then saving and refreshing:

const person = {};

Now open your browser's JavaScript console, enter person into it, and press Enter/Return. You should get a result similar to one of the below lines:

[object Object]

Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the JavaScript object in our file to look like this:

var person = {
  name: ['Bob', 'Smith'],
  age: 32,
  gender: 'male',
  interests: ['music', 'skiing'],
  bio: function() {
    alert(this.name[0] + ' ' + this.name[1] +
    ' is ' + this.age + ' years old. He likes ' +
    this.interests[0] + ' and ' + this.interests[1] + '.');
  },
  greeting: function() {
    alert('Hi! I\'m ' + this.name[0] + '.');
  }
};

NAfter saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:

person.name
person.name[0]
person.age
person.interests[1]
person.bio()
person.greeting()

You have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax!


Source of this example: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics