Forked from chadsansing/gist:ff00e262c0d462f7cba0
Last active
August 29, 2015 14:21
-
-
Save toolness/1ac6eea4d07a288bece5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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 usingthis
whenever possible. It's actually possible to avoid the use ofthis
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 withMath.random()
, you can ignore this!)