原型模式

2020-10-11  本文已影响0人  小宇cool

原型模式

概念 :

原型模式(Prototype): 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的的对象

这些概念在JavaScript中的原型继承是同一个意思.

JavaScript的继承主要提供原型链来实现

简单了解一下构造函数

原型和实例关系,每一个构造函数都有一个原型对象prototype,原型对象都包含一个指向构造函数的指针constructor, 而实例都包含一个指向原型对象的内部指针__proto__; 所以构造函数的原型默认是等于实例的原型proto

所以我们可以通过改变原型对象的指针来实现原型继承

场景一 利用 Es6 extends 关键字

// 父类
class Parent{
    constructor(name){
        this.name = name;
    }
    showName(){
        console.log(this.name);
    }
}
class ChildA extends Parent{
    constructor(name,age){
        // 调用父类的构造函数
        super(name);
        this.age = age
    }
    showAge(){
        console.log(this.age);
    }
}
class ChildB extends Parent{
    constructor(name,sex){
        super(name)
        this.sex = sex
    }
        showSex() {
        console.log(this.sex);
    }
}
let childa = new ChildA("张三",43);
console.log(childa.showAge());// 43
console.log(childa.showName());//张三
let childb = new ChildB("张三", '男');
console.log(childb.showSex());//男

场景二 利用 Object.create

// Shape - 父类(superclass)
function Shape() {
    this.x = 0;
    this.y = 0;
}
// 父类的方法
Shape.prototype.move = function (x, y) {
    this.x += x;
    this.y += y;
    console.info('Shape moved.');
}; 
// 子类
function Rectangle(){
    Shape.call(this)//call super constructor
}
// 子类继承父类
Rectangle.prototype = Object.create(Shape.prototype);
// 因为此时Rectangle的原型指向了Shape的原型, 所以原型的constructor指针指向了Shape
// 将子类原型的构造函数修复为自身
Rectangle.prototype.constructor = Rectangle;

console.log(new Rectangle().move());// Shape moved.

场景三 利用中间子类实现

function F(){
            this.name = "class"
        };
        F.prototype.sayHi = function(){};

        function G(){
            // 调用父类的构造函数,并改变this指向
            F.call(this)
        }
        //空函数 
        function Fn(){};
        // 将 Fn的原型 指向F 的原型
        Fn.prototype = F.prototype;
        // 将 G构造函数的原型指向指向一个新的fn对象, 正好指向了F
        G.prototype = new F();
        // 将 G函数的原型构造函数修复为G, 因为上面用prototype将G的构造函数的指向了Fn的函数
        G.prototype.constructor = G;
        // 继续在G函数身上定义方法
        G.prototype.sayName = function(){
            console.log(this.name);
        }
        let f = new F();
        console.log(new G());

总结: 多个类使用到了相同的属性和方法, 那我们就可以通过原型继承的方式来创造出类或者实例对象.

上一篇 下一篇

猜你喜欢

热点阅读