Skip to content

Instantly share code, notes, and snippets.

@richjava
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richjava/c494e363dbb450a074b0 to your computer and use it in GitHub Desktop.
Save richjava/c494e363dbb450a074b0 to your computer and use it in GitHub Desktop.
Intro to javascript custom objects
//modified from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
//class (can also be defined as anonymous function in the form of var Person = function () {...};)
function Person(firstName) {
//property
this.firstName = firstName;
// method (using anonymous function)
this.skyte = function() {
return "I'll be famous some day. Remember my name: " + firstName + "!";
}
}
//instantiation of objects
var person1 = new Person('Mary');
var person2 = new Person('John');
// show the firstName property of the objects
console.log('person 1 is ' + person1.firstName);
// outputs "person1 is Alice"
console.log('person 2 is ' + person2.firstName);
// outputs "person2 is Bob"
//call Person class's skyte method
console.log(person1.skyte());
//define static variable for Person class (shared by all instances)
Person.resperatorySystem = "lungs";
//define static method for Person class (shared by all instances)
//and use static variable
Person.breathe = function() {
return "I am breathing through my "+ Person.resperatorySystem;
};
//show output of static method
console.log(Person.breathe());
//use a prototype method to define a new method for the Person class
Person.prototype.sayHello = function() {
return "Hi, I'm " + this.firstName;
};
//show output of the prototype method
console.log(person1.sayHello());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment