javascript - JS中子类的实例属性为什么可以访问父类的实例属性?

查看:78
本文介绍了javascript - JS中子类的实例属性为什么可以访问父类的实例属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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属性呢?

解决方案

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

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();

这篇关于javascript - JS中子类的实例属性为什么可以访问父类的实例属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆