JavaScript 类(class) super 关键字
实例
实例
以下实例创建的类 "Runoob",并使用 super 调用父类 "Site" 的构造方法 :
classSite{constructor(name){this.sitename = name;
}present(){return'我喜欢' + this.sitename;
}}classRunoobextendsSite{constructor(name, age){super(name);
this.age = age;
}show(){returnthis.present() + ', 它创建了 ' + this.age + ' 年。';
}}letnoob = newRunoob("菜鸟教程", 5);
document.getElementById("demo").innerHTML = noob.show();
尝试一下 »
定义和用法
super 关键字用于访问和调用一个对象的父对象上的函数。。
在构造函数中使用时,super关键字将单独出现,并且必须在使用 this 关键字之前使用。super 关键字也可以用来调用父对象上的函数。
语法
super(arguments); // 调用父构造函数 super.parentMethod(arguments); // 调用父方法
技术细节
JavaScript 版本: | ECMAScript 2015 (ES6) |
浏览器支持
super 是 ECMAScript6 (ES6) 特性。
目前所有主流浏览器都支持 ES6 (JavaScript 2015) 。
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
Internet Explorer 11 或更旧版本的 IE 不支持 super 关键字。
更多实例
在类中使用 super:
实例
classPolygon{constructor(height, width){this.name = 'Rectangle';
this.height = height;
this.width = width;
}sayName(){return'Hi, I am a ' + this.name + '.';
}getarea(){returnthis.height * this.width;
}setarea(value){this._area = value;
}}classSquareextendsPolygon{constructor(length){// 这里,它调用父类的构造函数的,// 作为 Polygon 的 height, widthsuper(length, length);
this.height; // 需要放在 super 后面,不然引发 ReferenceErro// 注意:在派生的类中,在你可以使用'this'之前,必须先调用 super()。// 忽略这,这将导致引用错误。this.name = 'Square';
}}
尝试一下 »
用 super 调用父类的静态方法:
实例
classRectangle{constructor(){}staticlogNbSides(){return'I have 4 sides';
}}classSquareextendsRectangle{constructor(){}staticlogDescription(){returnsuper.logNbSides() + ' which are all equal';
}}Square.logDescription(); // 'I have 4 sides which are all equal'
尝试一下 »