Created
October 16, 2013 02:41
-
-
Save t0dd/7001837 to your computer and use it in GitHub Desktop.
Exploring JS topics - Objects and Inheritance
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
/* =========== JavaScript Objects =================== */ | |
//Prototypes & Inheritance | |
//Creates a custom prototype object using inherit() | |
var book = { | |
title: "", | |
author: "", | |
ISBN: null | |
}; | |
var book1 = inherit(book); //book is prototype for book1 | |
book1.publishYear = 1994; //adds a new property | |
book1.title = "This is my book"; //Change book1 title | |
book.title = "blank"; //change prototype title | |
var book2 = inherit(book); //creates new book object | |
//Prints book1 year & title | |
console.log("book1 = " + book1.publishYear + " " + book1.title); | |
//Prints prototype title | |
console.log("book = " + book.title); | |
//Prints book2 title which is inherited from prototype | |
console.log("book2 = " + book2.title); | |
//Property subtitle does not exist --> undefined | |
console.log("book2 subtitle = " +book2.subtitle); | |
//Delete a property | |
delete book1.publishYear | |
console.log("\nbook1 - removing property: " + book1.publishYear + " " + book1.title); | |
//Testing properties | |
console.log("book is enumerable? " + book.propertyIsEnumerable("title")); | |
console.log("book2 has own author property? " + book2.hasOwnProperty("author")); | |
//Iterate through properties | |
for(p in book){ | |
console.log("book property: " + p); | |
} | |
for(p2 in book1){ | |
console.log("book1 properties: " + p2); | |
} | |
for(p2 in book1){ | |
if(!book1.hasOwnProperty(p2)) continue; | |
console.log("book1 NON inherited properties: " + p2); | |
} | |
//ECMAscript5 alternative | |
console.log("Using Object.keys()" + Object.keys(book1)); | |
function inherit(p){ | |
if(p == null) | |
throw TypeError(); //p must be a non-null object. | |
if(Object.create) // If Object.create() is defined... | |
return Object.create(p); //then just use it. | |
var t = typeof p; // Otherwise do some more type checking | |
if (t !== "object" && t !== "function") throw TypeError(); | |
function f() {}; // Define a dummy constructor function. | |
f.prototype = p; // Set its prototype property to p. | |
return new f(); // Use f() to create an "heir" of p. | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment