I have to write all actors from array, each one should be on the new line. So far I have this code.
class Movie {
constructor(movieName, releaseDate, actors) {
this.movieName = movieName;
this.releaseDate = releaseDate;
this.actors = actors;
}
printDetail() {
console.log(this.movieName);
console.log(this.releaseDate);
function actrs() {
for (let i = 0; i < Movie.actors.length; i++) {
console.log("test if this actually works");
}
}
actrs();
}
}
let movie1 = new Movie("moviename", "releasedate", ["John Jackies", "Jack Johnies"]);
movie1.printDetail();
So, I am talking about "for" cycle. How can I define the array length of it? Whatever I do, I always get this error: "Uncaught TypeError: Cannot read properties of undefined (reading 'length')".
You're accessing a static (but undefined) property of Movie, while actors is a member property defined when a new Movie instance is constructed.
The actors property should be accessed using the this keyword, which refers to the Movie instance.
for (let i = 0; i < this.actors.length; i++) { /* ... */ }
// or
this.actors.forEach((actor) => { /* ... */ });
Use the instance variable instead. Also, remove the actrs function since it is unneeded and changes the value of this.
class Movie {
constructor(movieName, releaseDate, actors) {
this.movieName = movieName;
this.releaseDate = releaseDate;
this.actors = actors;
}
printDetail() {
console.log(this.movieName);
console.log(this.releaseDate);
for (let i = 0; i < this.actors.length; i++) {
console.log("test if this actually works");
}
}
}
let movie1 = new Movie("moviename", "releasedate", ["John Jackies", "Jack Johnies"]);
movie1.printDetail();
A few things here. You are referring to Movie. Which has no static fields or methods. What you want is your instance of it. The correct way to do this, as you know, is using the this keyword.
I'm guessing you tried it in your for-loop, but it didn't work. This is because the this context is different in a function. For it to work, you will have to change Movie.actors.length to this.actors.length, and then bind the function after its declaration:
const boundActrs = actrs.bind(this);
actrs();
This will get it to work. An alternative is to use an arrow function, which doesn't change the this context:
const actrs = () => {
for (let i = 0; i < this.actors.length; i++) {
console.log("test if this actually works");
}
}
However, this isn't clean code. I would make this a private function, or just have the for-loop in printDetail without the extra function.