Reputation: 2064
I'm doing a homework and I'm required to create a class so the code behaves as expected.
// This is the test input
movie = new Movie("Star Wars");
// Expected Output
[Movie "Star Wars"] // Expected output
My question is how do I get to it?
As I understand it they are asking me to write a class in ES5. Here is my code so far
var Movie = function Movie(title) {
this.title = title;
this.header = this.title = (title) ? "[Movie \"" + title + "\"]": "[Movie]";
this.show = function(){
console.log('Your movie is on theaters');
}
}
movie = new Movie("Lord Of The Rings"); // [object Object]
Am I missing something here?
UPDATE 1: Here is the code that solves it, as @loïc-faure-lacroix suggested.
var Movie = function Movie(title) {
this.title = title;
this.header = this.title = (title) ? "[Movie \"" + title + "\"]": " [Movie]";
this.show = function(){
console.log('Your movie is on theaters');
}
}
movie = new Movie("Lord Of The Rings"); // [Movie "Lord of The Rings"]
movie = new Movie(); // [Movie]
Upvotes: 1
Views: 53
Reputation: 13600
What you're looking for is a way to convert an object to a string. Unless you're adding the object to a html element, then what you're looking for is to define a toString
method.
Movie.prototype.toString = function () {
return this.title
}
It will show the object in the console in some interpereter, but it's not clear if its supported by all consoles.
Technically, it won't work as some consoles like firefox will use a fancy link to an object. But if you want to concatenate it to a string, then it will call toString and convert the object to string approriately. But the output of a raw object without transformation to string is, as far as I know, undefined.
Note:
It's useless to do the following because you already defined the function named Movie:
var Movie = function Movie() { ...}
Upvotes: 2