0

The point of this is to attach multiple tags (example: sci-fi, aliens, spaceships) when a user registers a new book, and chooses from an already existing set of tags. There is more to this but for simplification purposes this is all I ask. For example, can the property tags have multiple values, like be an array, so I can access them after?

Like the tags you put on a question when you ask it here.

class Book{
   constructor(title, cover, autor, tags){
      this.title = title;
      this.cover = cover;
      this.autor = autor;
      this.tags = tags;
}
4
  • yeah 100% - objects are kind of a big deal :) javascript is great for playing around because it's so loosely typed. Each time you instantiated a new Book() you could pass in any data type you like. Commented May 16, 2018 at 18:30
  • check out my answer on how to use your constructor, and access the object created. hope it helps Commented May 16, 2018 at 18:35
  • Yes, a property can have an array as a value, if that's what you're asking for. Commented May 16, 2018 at 18:38
  • Ok that is what I taught I should have tested it myself but I wanted a good explanation. Thank you all. Commented May 16, 2018 at 19:24

3 Answers 3

1

Yes, an object property can be an array. Your code is fine.

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

Comments

0

Sure, you can have arrays and properties in classes.

1 Comment

"and" makes no sense here
0

So you've got your constructor:

class Book{
  constructor(title, cover, author, tags){
    this.title = title;
    this.cover = cover;
    this.author = author;
    this.tags = tags;
}

Now all you need to do is instantiate it, and access it:

// presuming you have the params to pass in from somewhere
var someBook = new Book(title, cover, author, tags);

//to access, use either syntax styles:
var someBooksTags = someBook['tags']  // name of prop accessing as string
var someBooksTitle = somebook.title;

You will get the type back that you put in to the constructor, so if you pass an array of strings/objects as the tags, then that's what you'll get back when you access it.

If you've got any questions, feel free to ask dude.

Edit: Here's an example with a tags array passed in:

var nb_name = 'Awesome Book',
    nb_cover = '../../images/awesomebookcover.png',
    nb_author = {
        name: 'jimbo slim',
        booksPublished: 17
    },
    nb_tags = ['awesome','seasoned author','hardback'];

var book = new Book(nb_name, nb_cover, nb_author, nb_tags);

console.log(book.tags); 
// output: ['awesome','seasoned author','hardback']

Comments

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.