JS实现继承的3种方式

这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战markdown

  • 一、 原型继承方式app

    function Person(name,age){
        this.name = name;
        this.age = age;
    }
    
    Person.prototype.sayHello = function(){
        console.log("使用原型获得名字:%s,年龄:%d",this.name,this.age);
    }
    
    function Student(){
    
    }
    Student.prototype = new Person("Jay",37);
    Student.prototype.grade=5;
    Student.prototype.tips=function(){
        console.log("我是从Student来的,年级是%d,继承来的%s",this.grade,this.name);
    }
    
    var stu = new Student();
    stu.tips();
    复制代码
    • 首先咱们建立一个方法做为父类Person,再建立一个方法做为子类Student,子类用原型去接收父类构造函数,这样作一个指向关系从而达到子类继承父类方法。子类也能够添加本身的方法,这样最后在实例化子类Student的时候,能够从原型上拿到父类指向的函数。利用了原型链的特性每一级别的查找。

    二、 构造函数方式函数

    //父类函数
    function Parent(name){
        this.name = name;
        this.sayHello = function(){
            console.log("Parent Name : %s",this.name);
        }
    }
    
    //子类函数
    function Child(name,age){
        this.tempMethod = Parent;
        this.tempMethod(name);
        this.age = age;
        this.sayChild = function(){
            console.log("Child Name:%s,Age:%d",this.name,this.age);
        }
    }
    //测试继承
    var p = new Parent("Kvkens");
    p.sayHello();
    
    var c = new Child("Kvkens",29);
    c.sayChild();
    复制代码
    • 构造函数是用到了一个中间函数做为中间人,接收Parent函数,而且调用中间函数传入相应构造参数,这里可以直接调用Parent是由于固然环境是实例化,都是在new的时候发生的,并非静态的函数。

    三、 call、apply 方式post

    function Animal(name,age,love){
        this.name = name;
        this.age = age;
        this.love = love;
        this.sayHi = function(){
            console.log("Animal name:%s,age:%d,love:%s",this.name,this.age,this.love);
        }
    }
    
    function Dog(name,age,love){
        Animal.call(this,name,age,true);
    }
    var dog = new Dog("xiaobai",5,true);
    dog.sayHi();
    复制代码
    • 很是简单的继承实现,采用侵入式做用域劫持方式,我说的和别人解释的不同,只是我本身的理解,如说的不对请指出,代码会写,有的时候却不能说出为何是这样,都是本身的理解,见谅!
相关文章
相关标签/搜索