Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Objects
//Objects // Object Literal var person = { firstName: 'Bird', lastName: 'Graves', age: 20, children: ['Max', 'Angel', 'Bosco'], address: { street: '555 something st', city: 'A City', state: 'AC' }, fullName: function(){ return this.firstName +" "+this.lastName; } } //remember to check all your commas or you might be staring at the wrong section for 10 minutes wondering why its not working... *facepalm* print(person.firstName); var children = ['Max', 'Angel', 'Bosco'] children.forEach (function(child){ print(child); }) // for full address: print(person.address); //it just shows up as 'object object", but thats alright. //if you only want part of the address, eg: city, you put it after address: print(person.address.city); print(person.fullName()); //Object Constructor //create a new object var apple = new Object(); apple.color = 'red'; apple.shape = 'round'; //a function apple.describe = function(){ return 'An apple is the color '+this.color+' and is the shape '+this.shape+'.'; } print(apple.describe()); //YAY it works! // dont forget- a function needs "()"! // A simpler way to do this would be to use a Constructor Pattern. //Constructor Pattern function Fruit(name, color, shape){ this.name = name; this.color = color; this.shape = shape; this.describe = function(){ return 'A fruit that is '+this.color+' and '+this.shape+' is a '+this.name+'.'; } } //create new fruit - all you have to do is this line instead of the whole thing for each fruit- var pear = new Fruit('pear', 'green', 'round'); print(pear.describe()); // you can add arrays of objects var users = [ { name: 'John Doe', age: 30 }, { name: 'Macy Pacs', age: 23 }, { name: 'Josh Han', age: 63 } ]; print(users[1].age);
run
|
edit
|
history
|
help
0
sortStack
An awkward iteration
WC
Java - Looping thru Strings
greeting
Just stop thinking about it and go eat
My first app
BaseConverter
Javascript Closure
BinaryGap, javascript - Find longest sequence of zeros in binary representation of an integer.