JavaScript继承模式

好久不见. 提交于 2020-03-07 20:33:10

继承发展:
1.传统形式 ————> 原型链
过多的继承了没用的属性
2.借用构造函数
不能继承借用构造函数的原型
每次构造函数都要多走一个函数

栗子:

        function Person(name, age, sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        }

        function Student(name, age, sex, grade) {
            Person.call(this, name, age, sex);
        }
        var student=new Student();

3.共享原型
不能随便改动自己的原型

栗子:
1.

        Father.prototype.lastName = 'Deng';
        function Father() {}
        function Son() {}
        // 一个原型给了两个函数
        Son.prototype = Father.prototype;
        var father = new Father();
        function inherit(Target, Origin) {
            Target.prototype = Origin.prototype;
        }
        inherit(Son, Father);
        // 先继承后调用
        var son = new Son();

4.圣杯模式

栗子:
1.

        function inherit() {
        function F() {}
        F.prototype = Origin.prototype;
        Target.prototype = new F();
        Target.prototype.constuctor = Target;
        Target.prototype.uber = Origin.prototype;
        }
        Father.prototype.lastName = 'Deng';

        function Father() {}

        function Son() {}
        inherit(Target, Origin);
        var son = new Son();
        var father = new Father();

闭包的作用:可以实现封装,属性私有化

        function Deng(name, wife) {
        var preparewife = 'xiaozhang';
        this.name = name;
        this.wife = wife;
        this.divorce = function() {
            this.wife = preparewife;
        }
        this.changePreparewife = function() {
            preparewife = target;
        }
        this.sayPreparewife = function() {
            console.log(preparewife);

        }
        }
        var deng = new Deng('deng', 'xiaoliu');
         var inherit = (function() {
        var F = function() {}
        return function(Target, Origin) {
            F.prototype = Origin.prototype;
            Target.prototype = new F();
            Target.prototype.constuctor = Target;
            Target.prototype.uber = Origin.prototype;
        }
        }())
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!