Adding another function to an object

Hi there,

I am at the “Objects” subject, chapter 6. Methods.

the exercise


Add another method to your object literal. This method, .takeOff() , should console.log() the string 'Spim... Borp... Glix... Blastoff!' .

I thought (stupidly?) that I can add it just like adding another key-value pair, like:

alienShip.takeOff() = takeOff(){console.log( 'Spim... Borp... Glix... Blastoff!')};

Completely not correct of course, But, is there a way to add a function in an object other just like typing in it a new one?

The solution was:

let alienShip = {
  retreat() {
  takeOff() {
    console.log('Spim... Borp... Glix... Blastoff!')

I expected form that exercise something more than just go back in the editor and typing the new function method in it.

I am a total beginner, 20 days in programming in my 40s :slight_smile:

Hello, @script6093927419! Welcome to the forum.

You could do this:

alienShip['takeOff'] = function() {
  console.log('Spim... Borp... Glix... Blastoff!');

This would add takeOff() as a function or method of the alienShip object, but it is a simpler approach to just add the method directly to the object literal when you have easy access to the code.

Oh thank you so much midliner!
I only wanted to know that as a possibility in order to strengthen my understanding!
I am also always for the simple solutions too!


1 Like