这是我实现继承的代码:
<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 显示继承的父类的“父”,但现在,它只显示未定义。
我不知道为什么它不从父属性继承。
在此先感谢您的帮助。