这是我实现继承的代码:
<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>
我需要Child console.log来显示继承的父类中的“parent”,但是现在它只显示undefined。
我不知道它为什么不从父属性继承。
提前感谢您的帮助。
答案 0 :(得分:0)
因为你从不调用函数Parent
,这就是设置属性的内容。如果你仔细查看inherit
函数,就会使用prototype
的{{1}}属性,但是你永远不会调用P
- 这是一件好事; P
应该致电Child
:
P
显然,这样做的缺点是,您必须在多个地方列出function Child(nameChild) {
Parent.call(this);
console.log("parentprop:" + this.parentName);
}
- 无论是在致电Parent
还是在inherit
。您可以通过在Child
中的子函数上设置父构造函数来缓解这种情况:
inherit
...所以var inherit = (function () {
var F = function () {
};
return function (C, P) {
F.prototype = P.prototype;
C.parent = P; // <==== The new bit
C.prototype = new F();
C.uber = P.prototype;
C.prototype.constructor = C;
}
}());
变为:
Child
如果您对完成层次结构感兴趣(支持调用“超级”方法等),您可能需要查看我的Lineage
toolkit。它是一个小工具包,可以自动化很多这样的东西,但是如果你想学习这些东西是如何工作的,那么源代码可能会有趣的阅读。还有一个wiki page显示多层,功能完整的继承,不使用使用function Child(nameChild) {
Child.parent.call(this);
console.log("parentprop:" + this.parentName);
}
(作为将其与使用Lineage
进行比较的方法)。