JavaScript Objects Cheat Sheet
This is a simple cheat sheet about JavaScript objects. It is just my collection of notes I have been collecting on using and working with JS objects.
// literal notation object
var james = {
job: "programmer",
married: false,
speak: function( feeling ) {
console.log("Hello, I am feeling " + feeling);
};
// property detection in objects with hasOwnProperty
if ( james.hasOwnProperty("job") ) {
console.log(james.job);
}
else {
james.job = "Student";
console.log(james.job);
}
// constructor notation logic
function Person(first, last, job, married) {
this.firstname = first;
this.lastname = last;
var age = 0; // age is private
this.job = job;
this.married = married;
this.speak = function() {
console.log("Hello");
};
// this public method return the age
this.getAge = function(){
return age;
};
// this is a private function
var toggleMarried(){
this.married = ! this.married;
};
}
// create a "gabby" object using the Person constructor
var gabby = new Person("student", true);
// inheritance with prototype
// chain of inheritance and going up the chain to find properties
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
this.isAlive = true;
}
function Penguin(name) {
this.name = name;
this.numLegs = 2;
}
function Emperor(name) {
this.name = name;
this.saying = "Waddle waddle";
}
// set up the prototype chain
Penguin.prototype = new Animal();
Emperor.prototype = new Penguin();
var myEmperor = new Emperor("Jules");
console.log( myEmperor.saying ); // should print "Waddle waddle"
console.log( myEmperor.numLegs ); // should print 2
console.log( myEmperor.isAlive ); // should print true
//Creating objects, properties and functions
var students = ["Joseph", "Susan", "William", "Elizabeth"]
var scores = [ [80, 70, 70, 100],
[85, 80, 90, 90],
[75, 70, 80, 75],
[100, 90, 95, 85] ]
var average = function( array ) {
var total = 0;
for (var i = 0; i < array.length; i++){
total += array[i];
}
return total / array.length;
};
// create a gradebook object
var gradebook = {};
// create a property for each of the students and give each corresponding scores
for ( var i = 0; i < students.length; i++ ){
gradebook[students[i]] = {};
gradebook[students[i]].testScores = scores[i];
}
// add a function to add a score to a student
gradebook.addScore = function(student, score){
this[student].testScores.push(score);
};
// add a function to get a student's average score
gradebook.getAverage = function( student ){
return average(this[student].testScores);
};