所以我试着按照这本名为" Head First:HTML5 Programming"这意味着我正在努力学习JavaScript。
我非常习惯像Java和C#这样的OOP语言,因为整个原型方面,JS对我来说是一个新手。下面的代码有两个函数,它们曾经是全局的。然而,在我将它们移动到我的对象创建代码之后,它完全停止了工作。
可能是语法错误或逻辑错误。但我似乎无法在任何地方指出它,因为调试不是我在JavaScript中所做的事情。
非常感谢帮助!
function makeMovie(title, genre, rating, showtimes) {
var movie = {
this.title: title,
this.genre: genre,
this.rating: rating,
this.showtimes: showtimes
getNextShowing: function() {
var now = new Date().getTime();
for (var i = 0; i < this.showtimes.length; i++) {
var showtime = this.getTimeFromString(this.showtimes[i]);
if ((showtime - now) > 0) {
return "Next showing of " + this.title + " is " + this.showtimes[i];
}
}
return null;
}
getTimeFromString: function(timeString) {
var theTime = new Date();
var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?)/);
theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
theTime.setMinutes( parseInt(time[2]) || 0 );
return theTime.getTime();
}
}
return movie;
}
var movie1array = ["3:00pm", "7:00pm", "11:00pm"];
var movie2array = ["5:00pm", "9:00pm"];
var movie1 = makeMovie("Plan 9 from Outer Space", "cult classic", 2, movie1array);
var movie2 = makeMovie("Forbidden Planet", "classic sci-fi", 5, movie2array);
这是我尝试调用JavaScript的HTML页面:
<!doctype html>
<html>
<head>
<title>The Webville Theater</title>
<script src="Movie.js"></script>
<meta charset="utf-8">
</head>
<body>
<script>
var nextShowing = movie1.getNextShowing();
document.innerHTML = nextShowing;
nextShowing = movie2.getNextShowing();
document.body.innerHTML = nextShowing;
</script>
</body>
</html>
答案 0 :(得分:2)
在一个对象中,属性不应该以'this'开头。 'this'用于函数声明。 每个属性/值对用逗号分隔。
简单例子:
var myObj = {
foo: 'bar',
test: 'foobar',
logFoo: function(){
console.log( this.foo)
}
}
myObj.logFoo(); // log : 'bar'
您的代码:
function makeMovie(title, genre, rating, showtimes) {
var movie = {
title: title,
genre: genre,
rating: rating,
showtimes: showtimes,
getNextShowing: function() {
var now = new Date().getTime();
for (var i = 0; i < this.showtimes.length; i++) {
var showtime = this.getTimeFromString(this.showtimes[i]);
if ((showtime - now) > 0) {
return "Next showing of " + this.title + " is " + this.showtimes[i];
}
}
return null;
},
getTimeFromString: function(timeString) {
var theTime = new Date();
var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?)/);
theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
theTime.setMinutes( parseInt(time[2]) || 0 );
return theTime.getTime();
}
}
return movie;
}
var movie1array = ["3:00pm", "7:00pm", "11:00pm"];
var movie2array = ["5:00pm", "9:00pm"];
var movie1 = makeMovie("Plan 9 from Outer Space", "cult classic", 2, movie1array);
var movie2 = makeMovie("Forbidden Planet", "classic sci-fi", 5, movie2array);