js中的super

1.this和super的区别:

  • this关键词指向函数所在的当前对象
  • super指向的是当前对象的原型对象

2.super的简单应用

const person = {
    name:'jack'
}

const man = {
    sayName(){
        return super.name;
    }
}

Object.setPrototypeOf( man, person );

let n = man.sayName();

console.log( n )    //jack

3.super的另类实现

super.name  
等同于   
Object.getPrototypeOf(this).name【属性】  
等同于   
Object.getPrototypeOf(this).name.call(this)【方法】

4.super中的this指向(易混淆)

super.name指向的是原型对象person 中的name,但是绑定的this还是当前的man对象。

const person = {
    age:'20多了',
    name(){
        return this.age;
    }
}

const man = {
    age:'18岁了',
    sayName(){
        return super.name();
    }
}

Object.setPrototypeOf( man, person );

let n = man.sayName();

console.log( n )    //18岁了

Object.getPrototypeOf(this).name指向的是person的name,绑定的this也是person

const person = {
    age:'20多了',
    name(){
        return this.age;
    }
}

const man = {
    age:'18岁了',
    sayName(){
        return Object.getPrototypeOf(this).name();
    }
}

Object.setPrototypeOf( man, person );

let n = man.sayName();

console.log( n )        //20多了

Object.getPrototypeOf(this).name.call(this)指向的是person的name,不过通过call改变了函数的执行上下文,所以this指向的还是man

const person = {
    age:'20多了',
    name(){
        return this.age;
    }
}

const man = {
    age:'18岁了',
    sayName(){
        return Object.getPrototypeOf(this).name.call(this)
    }
}

Object.setPrototypeOf( man, person );

let n = man.sayName();

console.log( n )    //18岁了
原文地址:https://www.cnblogs.com/pwindy/p/12666846.html