Last active
October 11, 2015 06:27
-
-
Save majgis/3816953 to your computer and use it in GitHub Desktop.
Javascript instantiable class experiments.
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
// Modified excerpt from: | |
// https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript | |
// define the Person Class | |
function Person(name) { | |
//Public property | |
this.name = name; | |
//Private property | |
this._whatever = '' | |
this.sayHello() | |
} | |
//Static method | |
Person.something = function(){ | |
} | |
//Public property | |
Person.prototype.somethingElse | |
//Private property | |
Person.prototype._KNOWN = {'mike':true, 'bob':true} | |
//Private method | |
Person.prototype._recognize = function(){ | |
return this._KNOWN[this.name]; | |
}; | |
//Public method | |
Person.prototype.sayHello = function(){ | |
if (this._recognize()){ | |
alert('hello ' + this.name); | |
} | |
}; | |
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
>p = new Person('mike') | |
(alert) | |
>p = new Person('fred') | |
(no alert) |
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
// Modified excerpt from: | |
// https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript | |
// define the Person Class | |
function Person() {} | |
// define the Student class | |
function Student() { | |
// Call the parent constructor | |
Person.call(this); | |
} | |
// inherit Person | |
Student.prototype = Object.create(Person.prototype); //A common mistake is to use new Person(); use es5shim if < ie8 for Object.create | |
// correct the constructor pointer because it points to Person | |
Student.prototype.constructor = Student; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript