javascript类式继承最优版

时间:2023-03-09 07:54:47
javascript类式继承最优版

直接看实例代码:

 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript类式继承</title>
</head>
<body>
<script>
var inherit = (function () {
var F = function () {};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.prototype.constructor = C;
C.uber = P.prototype;
};
} ()); function Person(name) {
this.name = name || "Adam";
}
Person.prototype.say = function () {
return this.name;
}; function Child(name, age, sex) {
Person.apply(this, arguments);
this.age = age;
this.sex = sex;
} inherit(Child, Person); Child.prototype.getAge = function () {
return this.age;
};
Child.prototype.getSex = function () {
return this.sex;
}; var c = new Child('fengyuqing', 23, 'male');
console.log(c.say());
console.log(c.getAge());
console.log(c.getSex());
</script>
</body>
</html>