Skip to content

Instantly share code, notes, and snippets.

@toolness
Forked from chadsansing/gist:ff00e262c0d462f7cba0
Last active August 29, 2015 14:21
Show Gist options
  • Save toolness/1ac6eea4d07a288bece5 to your computer and use it in GitHub Desktop.
Save toolness/1ac6eea4d07a288bece5 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script>
function randomObject() {
function Dessert(name, taste, texture) {
this.name = name;
this.taste = taste;
this.texture = texture;
}
var chocolatePudding = new Dessert("Chocolate pudding", "rich", "gooey");
var cheeseCake = new Dessert("Cheese cake", "tart", "smooth");
var oatmealRaisinCookies = new Dessert("Oatmeal-raisin cookies", "sweet", "chewy");
var desserts = [chocolatePudding, cheeseCake, oatmealRaisinCookies];
var dessert = desserts[Math.round(Math.random() *(desserts.length-1))];
document.getElementById("myObject").innerHTML = "<div>" + dessert.name + " is/are " + dessert.taste + " and " + dessert.texture + ".</div>"
}
</script>
</head>
<body>
<p><button onClick="randomObject()">Click me!</button></p>
<div id="myObject"></div>
</body>
</html>
@toolness
Copy link
Author

Ok @chadsansing, I've fixed this so it works, and you can see the differences between your original version and my fixes in the revisions section of this gist.

However, just because it works doesn't actually mean it's code that follows best practices. JavaScript is actually a notoriously complicated language with lots of confusing features:

The language is burdened with too many features, including many that interact badly or were poorly designed. It is a language that has, as Emperor Joseph would say, too many notes.

One of my least favorite features of JavaScript is the this keyword, and that's one of the main reasons your code didn't work--or at most, might have worked, but would've caused some weird confusing side effects. Because of this, I tend to try to avoid using this whenever possible. It's actually possible to avoid the use of this entirely, but doing so is a stylistic choice that some people disagree with.

The other reason your code didn't work was because the functionality to get a random dessert was broken, but it might've been easier to just use _.random() or copy-paste something from MDN. I usually do one of those myself in my own code, because those kinds of problems have been solved many times before, and writing a solution from scratch can be error-prone. (That said, if your learning objective was to learn how to do things with Math.random(), you can ignore this!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment