javascript - JS中子类的实例属性为什么可以访问父类的实例属性?
PHPz
PHPz 2017-04-11 12:21:59
[JavaScript讨论组]
class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  
  test() { }
}

class Student extends Person {
  constructor(name, age, no) {
    super(name, age)
    this.no = no
  } 

  say() {
    console.log(`name: ${this.name}, age: ${this.age}, no: ${this.no}`)
  }
}

let student = new Student('mrcode', 21, '11403080435')

student.say()

student可以访问test方法,这点可以理解。 但是为什么通过Student中的this可以访问到父类中的name, age呢? ES6中的class只是原型链的语法糖。 原型链上的对象都是原型。 哪里来的name, age属性呢?

PHPz
PHPz

学习是最好的投资!

全部回复(4)
PHPz

super(name,age))相当于原始寄生组合继承中的 Person.call(this,name,age)

黄舟

ES6的class是语法糖,但不是原型链的语法糖。其背后实现还是通过伪经典继承,调用super关键字,就类似于调用了ES5中的Super.apply(this,arguments)【具体浏览器实现不是这样实现的】

阿神

super 就是继承父类的属性

大家讲道理

翻译过来基本就是这个样子

function Person(name,age){
    this.name=name;
    this.age=age;
}

Person.prototype.test=function(){
    console.log("~~~prototype test~~~")
}

function Student(name,age,no){
    Person.apply(this,[name,age]);//super(name, age)
    this.no=no;
}

//extend
Student.prototype=(function(){
  var tempObject=function(){};
  tempObject.prototype=Person.prototype;
  return new tempObject();
}());
Student.prototype.constructor=Student;
//定义Student类的say函数
Student.prototype.say=function(){
    console.log("name:%s,age:%s,no:%s",this.name,this.age,this.no);
}

var student_instance = new Student('mrcode', 21, '11403080435')

student_instance.say();
student_instance.test();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号