class基本構文と継承
14521 ワード
class基本構文と継承
1.classについて
クラスの定義
class Person{
constructor(skin,language){
this.skin=skin;
this.language=language;
}
say(){
console.log('I am a Person')
}
}
classは本質的にfunctionであるため、prototype属性を持ち、newがclassである場合、classのporototype属性をこの新しいオブジェクトのproto属性に付与します.(prototypeは関数の属性であり、ポインタである.コンストラクション関数の場合、prototypeはコンストラクション関数としての属性である.prototypeはオブジェクトであってもよく、prototypeはオブジェクトインスタンスのプロトタイプオブジェクトである.したがってprototypeは属性であり、オブジェクトである.newのオブジェクトの場合、オブジェクトにptotype属性がないと理解できるので、ptotypeをオブジェクトのprotoに与える.
console.log(typeof Person); // function
let p = new Person('unkown','unknown');
console.log(p); // Person {skin: "unkown", language: "unknown"}
console.log( __proto__==Person.prototype); // ture
newオブジェクトの場合、javascript高度なプログラム設計から抜粋して、次の手順に従います.
2.constructorメソッド
constructorメソッドはデフォルトのメソッドで、newオブジェクトの場合に自動的に呼び出されます.クラスにはconstructorが必要です.定義されていない場合は、デフォルトで追加されます.
constructor() {}
3.classの継承
オブジェクト向けの特徴の一つは継承であり、exendsキーワードを使用していない場合、jsの継承はサブクラスのプロトタイプオブジェクトを変更して継承コードを完了することを使用します.function User(name,age){
this.name=name
this.age=age
}
User.prototype.show=function(){
console.log(" ")
}
function VipUser(type){
this.type=type
}
VipUser.prototype=new User("joker",'age')
VipUser.prototype.constructor=VipUser
let vipUser=new VipUser("ViP")jav
でextendsを使用するとclass User {
constructor(name,age){
this.name=name
this.age=age
}
show(){
console.log(" ")
}
}
class VipUser extends User{
constructor(name,age,type){
super(name,age)//
this.type=type
}
show(){
" vip "
}
}
let vipUser=new VipUser("joke","20","vip")
//superが書かなければなりません.親の構造からデータを取得することを示すサブクラスに構造メソッドがない場合、デフォルトの構造メソッドclass VipUser extends User {
}
//
class VipUser extends User {
constructor(...args) {
super(...args);
}
}
が呼び出されます.superは親オブジェクトを表し、superによって親メソッドclass VipUser extends User{
constructor(name,age,type){
super(name,age)//
super.show=function(){
console.log(" vip ")
}
}
}
4.サブクラスオブジェクトのインスタンス化
を書き換えることができます.サブクラスオブジェクトは親のプロパティとメソッドを持ち、サブオブジェクトは独自のプロパティとメソッドを持つことができます.例えばchineseは親のsayメソッドを継承し,独自のchinese sayメソッドも持つ.最後の2行のコード表示let american = new American('white','English');
let chinese =new Chinese('yellow','chinese','changsha');
chinese.say();//I am a Person
chinese.chinesesay();//I am a Person I am a Chinese
console.log(American.__proto__===Person);//true
console.log(American.__proto__);//
console.log(American.prototype.__proto__===Person.prototype);//true