- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Inheriting_properties
- http://javascript.info/tutorial/inheritance#looping-with-without-inherited-properties
function inherit(child, parent) {
child.parent = parent;
child.prototype = Object.create(parent.prototype);
child.prototype.constructor = child;
}
var Dad = (function () {
var age = 40;
var cls = function () {
this.data = [];
};
cls.prototype.foo = function () {
console.log(this, this.age());
};
cls.prototype.age = function () {
return age;
};
return cls;
}());
var Son = (function () {
var cls = function () {
cls.parent.call(this);
this.prop = 8;
};
inherit(cls, Dad);
cls.prototype.age = function () {
return cls.parent.prototype.age.call(this) - 18;
};
return cls;
}());
var a = new Dad();
var b = new Son();
a.foo();
b.foo();
When you define a function
function foo () {};
or
var foo = function () {};
the interpreter creates (only the properties we are interested in are shown):
foo()
prototype : Object
constructor : foo ()
__proto__ : function ()
Note, that:
foo.constructor === foo.prototype.constructor; // false
foo.constructor === foo.__proto__.constructor; // true
When you execute new foo()
or new foo
(the first way allows you to pass some arguments, while the last doesn't):
- A new object is created, inheriting from
foo.prototype
. - This object named
this
is passed to thefoo
and returned from it.
Note that foo.prototype.constructor
points to the foo
itself by default.
We can changed both foo.prototype
and foo.prototype.constructor
before the new foo
call. Lets see what we'll get:
function foo () {
this.country = 'Italy';
}
var a = new foo(); // Object { country: "Italy" }
var b = new foo.prototype.constructor(); // Object { country: "Italy" }
var c = new foo.__proto__.constructor(); // function anonymous()
a instanceof foo; // true
b instanceof foo; // true
c instanceof foo; // false
The both a
and b
have the following structure:
country : "Italy"
__proto__ : Object
constructor : foo()
Lets change the constructor only:
function foo () {
this.country = 'Italy';
}
function moo () {
this.food = 'pizza';
}
foo.prototype.constructor = moo;
var a = new foo(); // Object { country: "Italy" }
var b = new foo.prototype.constructor(); // Object { food: "pizza" }
a instanceof foo; // true
b instanceof foo; // false
b instanceof moo; // true
a.constructor; // function moo()
You can see that changing the constructor has no effect for objects creation with new foo
. What is the constructor
property for? Have no idea.