继承

# 继承

参考:https://github.com/yygmind/blog/issues/7

1、原型链继承

  • 过多的继承了没用的属性
				Father.prototype.lastName = "Yan"
        function Father() {

        }
        var father = new Father()
        Son.prototype = father;
        function Son() {

        }
        var son = new Son()

2、借用构造函数

  • 不能继承借用构造函数的原型
  • 每次构造函数都要多走一个函数

通过 call 来让 Father 函数替 son 函数打工。帮他添加属性。(前提是 Son 函数是要通过 new 实例化)

				// 借用构造函数
        Father.prototype.lastName = "Yan";
        function Father(name) {
            this.name = name;
        }
        function Son(name, skill) {
            Father.call(this,name);
            this.skill = skill;
        }

        var son = new Son('xiaoming', 'football')
        

3、共享原型

  • 不能随便改动自己的原型
        // 3、共享原型
        Father.prototype.lastName = 'Yan';
        function Father(name) {
            this.name = name;
        }
        function Son(age) {
            this.age = age;
        }
        Son.prototype = Father.prototype;
        // Son.prototype = new Father('chen');
        var son = new Son(18)

4、圣杯模式

最终模式。

			// 4、圣杯模式
        Father.prototype.lastName = "yan";
        function Father(name) {
            this.name = name;
        }

        function Son(age) {
            this.age = age;
        }

        function extend(Target, Origin) {
            var Fn = function () { }
            Fn.prototype = Father.prototype;
            Target.prototype = new Fn();
            Target.prototype.constructor = Target;
        }
        extend(Son, Father);
        var son = new Son(18);