JS继承

70 阅读1分钟

继承就是让A找到B的属性方法

  1. 原型链继承 把Parent的实例赋值给Child的原型对象,这样Child的实例能通过原型链的方式找到Parent实例的属性和方法
        function Parent(name) {
            this.name = 'deibo';
        }
        Parent.prototype.getName = function () {
            console.log(this.name);
        }
        function Child() {
        }
        Child.prototype = new Parent();// 核心代码
        var child1 = new Child();
        child1.getName()//  打印出'deibo'
  1. 构造函数的继承 利用构造函数this和call,属于自身属性的复制
        function Parent(name) {
            this.name = 'deibo';
        }
        function Child(name) {
        Parent().call(this,name)
        }
        let childObj=new Child('tutu')
        console.log(childObj.name) //  输出'tutu'
  1. 组合继承
        function Parent(age) {
            this.age= 18    
        }
        function Son() {
           Parent.call(this)  
        }
        Parent.prototype.getName = function () { return this.name }
        Parent.prototype.name = 'tutu'
        let obj = new Parent()  
        }
  1. 类的继承
        class Parent {
            constructor(name, age) {
                this.name = name
                this.age = age
            }
            getName() {
                return this.name
            }
        }
        class Son extends Parent {
        }
        let obj =new Son('deibo',18)