javascript純面向對象開發需要使用到的一個模式,來對對象之間原型繼承做中間層代理避免重復繼承與代碼雜亂
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//父類
function Teacher(){}
Teacher.prototype.name = "teacher";
//子類
function Student(){}
Student.prototype.age = 18;
//原型繼承調用
inherit(Student,Teacher);
let s = new Student();
let t = new Teacher();
/*
*
聖杯模式原型繼承封裝
@param Target 需要繼承的子類
@param Origin 被繼承的父類
*/
function inherit(Target,Origin){
//創建中間層構造函數
function Buffer(){}
//把被繼承父類的原型付給中間層構造函數
Buffer.prototype = Origin.prototype;
//把實例化的中間層構造函數生成的對象付給需要繼承的目標類
Target.prototype = new Buffer();
//目標類構造函數指向歡原
Target.prototype.constructor = Target;
//定義目標類從哪繼承
Target.prototype.super_class = Origin;
}
console.log(s,t);
</script>
</body>
</html>
