Assessment wanted for Object basics 3 skill test

let cat = {
name : ‘Bertie’,
breed : ‘Cymric’,
color : ‘white’,
greeting: function() {
console.log(‘hello,said’+this.name[0]+’ the’+this.breed+’ ');
}
}

let cat2 = {
name : ‘pihu’,
breed : ‘deshi’,
color : ‘grey’,
greeting: function() {
console.log(‘hello,said’+this.name[0]+’ the’+this.breed+’ ');
}
}

let para1 = document.createElement(‘p’);
let para2 = document.createElement(‘p’);

para1.textContent = cat.greeting();
para2.textContent = cat2.greeting();

section.appendChild(para1);
section.appendChild(para2);

Hi @black_street_boy, welcome to the community!

Your code is looking pretty good here; your objects are well-formed, and you are outputting the strings to the console as expected.

I think you could do with improving the strings outputted by the object methods, for example:

  • Your spacing is not quite right - many of the words are joined together.
  • You are only including the first letter of each cat name, not the entire name, in each case.

A code update like so could fix this:

let cat = {
name : 'Bertie',
breed : 'Cymric',
color : 'white',
greeting: function() {
console.log('hello, said '+this.name+' the '+this.breed+' ');
}
}

let cat2 = {
name : 'pihu',
breed : 'deshi',
color : 'grey',
greeting: function() {
console.log('hello, said '+this.name+' the '+this.breed+' ');
}
}

Also, you don’t need to try to put the output strings inside paragraphs on this one. The strings are output to your browser’s devtools web console instead, using console.log(), so no paragraphs are needed. Just this would be fine:

cat.greeting()
cat2.greeting();
3 Likes

How would one make the code DRY :ocean::desert: ? For the methods, would you declare the function before the objects and call within, or something?

Disregard… " When an object instance is created from a class, the class’s constructor function is run to create it. This process of creating an object instance from a class is called instantiation — the object instance is instantiated from the class."

Guessing I’m about to learn just that!

@timandes yes, absolutely! In the next article or so, you’ll be running through creating classes in which you define methods, and then they are available on all instances of those classes.

function Cat(name, breed, color) {
this.name = name;
this.breed = breed;
this.color = color;
  this.greeting = function() {
    alert(`Hello, said ${this.name} the ${this.breed}.`);
  };
}

let cat1 = new Cat('Bertie', 'Cymric', 'white');
let cat2 = new Cat('Ophelia', 'Tabby', 'gray');

Would this be considered more ‘DRY’?

1 Like

@timandes yes indeed! Because you are defining the method on the constructor, you only need to do it once, then every object instance has it automatically. Great work.

2 Likes

I might just be progressing, haha. Thanks!

@timandes You totally are — keep rocking the JS!