Skip to content

Instantly share code, notes, and snippets.

@volodymyrprokopyuk
Last active March 1, 2016 14:45
Show Gist options
  • Save volodymyrprokopyuk/e95c82678be824544faf to your computer and use it in GitHub Desktop.
Save volodymyrprokopyuk/e95c82678be824544faf to your computer and use it in GitHub Desktop.
Javascript OOP
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