Here is my code to achieve my inheritance:
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Classical Pattern #5 - A Temporary Constructor (a pattern that should be generally avoided)
Description: first borrow the constructor and then also set the child's prototype to point to a new instance of the constructor
*/
/* Basic */
/*function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
}*/
/* Storing the Superclass */
/*function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
}*/
/* Resetting the Constructor Pointer */
/*function inherit(C, P) {
var F = function () {};
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}*/
/* in closure */
var inherit = (function () {
var F = function () {
};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}
}());
function Parent(name) {
this.nameParent = name || 'Adam';
this.parentName = "parent";//this.nameParent;
}
// adding functionality to the prototype
Parent.prototype.say = function () {
return this.nameParent;
};
// child constructor
function Child(nameChild) {
console.log("parentprop:" + this.parentName);
}
inherit(Child, Parent);
var kid = new Child();
console.log(kid.name); // undefined
console.log(typeof kid.say); // function
kid.nameParent = 'Patrick';
console.log(kid.parentName);
console.log(kid.say()); // Patrick
console.log(kid.constructor.nameParent); // Child
console.log(kid.constructor === Parent); // false
// reference
// http://shop.oreilly.com/product/9780596806767.do
</script>
</body>
I need the Child console.log to display “parent” from the parent class inherited, but for now, it only displays undefined.
I don’t know why it doesn’t inherit from parent property.
Thanks in advance for your help.
Because you never call the function
Parent, which is what’s setting the property. If you look closely at yourinheritfunction, you’re using theprototypeproperty ofPbut you’re never callingP— which is a good thing; it’sChildwho should callP:Obviously, this has the disadvantage that you have to list
Parentin more than one place — both in your call toinherit, and inChild. You could mitigate that by setting the parent constructor on the child function ininherit:…so then
Childbecomes:If you’re interested in doing hierarchies thoroughly (with support for calling “super” methods and such), you might want to look at my
Lineagetoolkit. It’s a small toolkit that automates a lot of this stuff, but if you want to learni how this stuff works, the source might make for interesting reading. There’s also a wiki page there showing multi-layer, fully-functional inheritance without usingLineage(as a means of comparing it with usingLineage).