Last active
March 1, 2016 14:45
-
-
Save volodymyrprokopyuk/e95c82678be824544faf to your computer and use it in GitHub Desktop.
Javascript OOP
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
var Parent = function(name) { // constructor | |
this.name = name; // own property | |
}; | |
// Function.prototype | |
(function(proto) { | |
// shared method | |
proto.toString = function() { return '** Parent ' + this.name; }; | |
})(Parent.prototype); | |
var Child = function(name) { | |
Parent.call(this, name); // constructor stealing | |
}; | |
Child.prototype = Object.create(Parent.prototype); // prototype chaining | |
(function(proto) { | |
// Function.prototype.constructor | |
proto.constructor = Child; | |
// method redefinition | |
proto.toString = function() { return '** Child ' + this.name; }; | |
})(Child.prototype); | |
var p = new Parent('PARENT'); | |
var ch = new Child('CHILD'); | |
console.log(p.toString()); // ** Parent PARENT | |
console.log(ch.toString()); // ** Child CHILD | |
// call parent method | |
console.log(Parent.prototype.toString.call(ch)); // ** Parent CHILD | |
console.log(p instanceof Parent); // true | |
console.log(p instanceof Child); // false | |
console.log(ch instanceof Parent); // true | |
console.log(ch instanceof Child); // true | |
console.log(p.constructor === Parent); // true | |
console.log(ch.constructor === Child); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment