码迷,mamicode.com
首页 > 编程语言 > 详细

javascript原型继承圣杯模式

时间:2019-02-09 17:54:24      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:head   func   面向对象   重复   调用   struct   targe   继承   开发   

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>

 

javascript原型继承圣杯模式

标签:head   func   面向对象   重复   调用   struct   targe   继承   开发   

原文地址:https://www.cnblogs.com/y-y-y-y/p/10357697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!