<p>Instead of passing the object to the <em>getNextShowing</em> function that takes a <em>movie</em> as an argument, we can move it inside the object and make it a method.</p>
<p>But there is a better way, create a <em>constructor</em>. See <a href="http://jsfiddle.net/lakenney/xrv6gopm/">http://jsfiddle.net/lakenney/xrv6gopm/</a>.
JavaScript
var movie1 = {
title: "Plan 9 from Outer Space",
genre: "Cult Classic",
rating: 2,
showtimes: ["3:00pm", "7:00pm", "11:00pm"],
getNextShowing: function () {
var now = new Date().getTime();
for (var i = 0; i < this.showtimes.length; i++) {
var showtime = getTimeFromString(this.showtimes[i]);
if ((showtime - now) > 0) {
return "Next showing of " + this.title + " is " + this.showtimes[i];
}
}
return null;
}
};
var movie2 = {
title: "Forbidden Planet",
genre: "Classic Sci-fi",
rating: 5,
showtimes: ["5:00pm", "9:00pm"],
getNextShowing: function() {
var now = new Date().getTime();
for (var i = 0; i < this.showtimes.length; i++) {
var showtime = getTimeFromString(this.showtimes[i]);
if ((showtime - now) > 0) {
return "Next showing of " + this.title + " is " + this.showtimes[i];
}
}
return null;
}
};
var banzaiMovie = {
title: "Buckaroo Banzai",
genre: "Cult Classic",
rating: 5,
showtimes: ["1:00pm", "5:00pm", "7:00pm"],
getNextShowing: function () {
var now = new Date().getTime();
for (var i = 0; i < this.showtimes.length; i++) {
var showtime = getTimeFromString(this.showtimes[i]);
if ((showtime - now) > 0) {
return "Next showing of " + this.title + " is " + this.showtimes[i];
}
}
return null;
}
};
function getTimeFromString(str) {
var theTime = new Date();
var time = str.match(/(\d+)(?::(\d\d))?\s*(p?)/);
theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
theTime.setMinutes( parseInt(time[2]) || 0 );
return theTime.getTime();
}
var nextShowing = movie1.getNextShowing();
console.log(nextShowing);
nextShowing = movie2.getNextShowing();
console.log(nextShowing);
nextShowing = banzaiMovie.getNextShowing();
console.log(nextShowing);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.