我是类和 OOP 的新手,在学习解释类和继承的教程时偶然发现了一些东西。
如何将属于基类构造函数的值传递给子类?
例如,如果一个 BASE 类有
this.name=name
this .age=age
子类继承基类
在基类中,有两个属性
this.childSchoool=school
this.childfiends=friends
我可以使用super().func;
访问基类的函数
如果我创建一个像这样的子类对象
let childobj = new child("school_name", 6);
它会用学校名称和年龄初始化子对象,但是
如何设置子类对象的name
和age
?
最佳答案
很简单,如果您有一个继承自另一个类 (classA) 的类 (classB),则在 classB 构造函数中,您将为 classA 构造函数获取参数并传递它们。
MDN对此进行了解释。
class Base {
constructor(name, age){
this.name = name;
this.age = age;
}
}
class Child extends Base {
constructor(name, age, school, friends){
super(name, age); //pass along to the Base constructor
this.school = school;
this.friends = friends;
}
}
let achild = new Child('ben', 4, 'School1', 99);
参数顺序很重要。但是,您也可以使用命名参数:
let bchild = new Child(school='school2', age=9, name='chris', friends=22);
或者您可以使用 spread syntax传入 map 或对象:
let amap = new Map([['name', 'sally'],['school', 'school1'],['age', 10],['friends', 9001]]);
let cchild = new Child(...amap);
关于javascript - 如何设置属于基类[继承]的子类对象的属性(属性)? (将 Base 的属性传递给 Child),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57690357/