JavaScript高级-----4.继承

2. 继承

2.1 call()

  • 可以调用某个函数
  • 可以修改函数运行时的this指向

<script>
    // call 方法
    function fn(x, y) {
        console.log(this); //修改之前this指向的是window,修改之后this指向的是o这个对象
        console.log(x + y); //3
    }
    var o = {
        name: 'andy'
    };
    // fn();传统的函数调用方法
    // 1. call() 可以调用函数
    fn.call(); //Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

    // 2. call() 可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象
    fn.call(o, 1, 2); //{name: "andy"}
</script>

2.2 利用构造函数继承父类的属性

ES6之前是利用构造函数继承父类的属性;利用原型对象继承父类的方法。
利用构造函数继承父类的属性的核心方法是:通过call把父类型的this指向子类型的this,这样就可以实现子类型继承父类型的属性。

<script>
    //借用父构造函数继承属性
    //1. 父构造函数
    function Father(uname,age){
        //这里的this原本指向父构造函数的实例对象
        this.uname = uname;
        this.age = age;
    }

    //2. 子构造函数
    function Son(uname, age){
        //这里的this指向子构造函数的对象实例
    }
</script>

现在上述两个构造函数没有任何关系,那么子构造函数如何才可以使用父构造函数的两个属性呢?思路:将父构造函数中的this指向改成子构造函数的实例对象。

<script>
    // 借用父构造函数继承属性
    // 1. 父构造函数
    function Father(uname, age) {
        // this 指向父构造函数的对象实例father
        console.log(this);
        this.uname = uname;
        this.age = age;
    }


    // 2 .子构造函数 
    function Son(uname, age, score) {
        // this 指向子构造函数的对象实例
        Father.call(this, uname, age); //在调用父类构造方法的同时,将父类的this指向改为son
        this.score = score; //这是子构造函数独有的属性
    }
    var son = new Son('刘德华', 18, 100); //Son {uname: "刘德华", age: 18, score: 100}
    console.log(son); //Son {uname: "刘德华", age: 18, score: 100}

    var farther = new Father('张学友', 20); //父构造函数的this指向还是指向父构造函数的实例对象 Father {uname: "张学友", age: 20}
</script>

2.3 借用原型对象继承父类型方法

之前提到:共有的属性写在构造函数里面,共有的方法写在原型对象里

3. ES5中的新方法

猜你喜欢

转载自www.cnblogs.com/deer-cen/p/12384506.html