Last active
March 27, 2017 02:58
-
-
Save abdulapopoola/5251693 to your computer and use it in GitHub Desktop.
Public, Private and Static Methods; JavaScript Style
This file contains hidden or 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
//Constructor | |
var Person = function (name, age){ | |
//private properties | |
var priv = {}; | |
//Public properties | |
this.name = name; | |
this.age = age; | |
//Public methods | |
this.sayHi = function(){ | |
alert('hello'); | |
} | |
} | |
// A static method; this method only | |
// exists on the class and doesn't exist | |
// on child objects | |
Person.sayName = function() { | |
alert("I am a Person object ;)"); | |
}; | |
// An instance method; | |
// All Person objects will have this method | |
Person.prototype.setName = function(nameIn) { | |
this.name = nameIn; | |
} | |
// Tests | |
var per = new Person('John Doe', 22); | |
//Shows alert | |
Person.sayName(); | |
//TypeError: Object [object Object] has no method 'sayName' | |
per.sayName() | |
//Show alert | |
per.sayHi(); | |
//John Doe | |
per.name; | |
//22 | |
per.age; | |
per.setName('Jane Doe'); | |
//Jane Doe | |
per.name; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment