- 小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
什么是class
class 声明创建一个基于原型继承的具有给定名称的新类。类也是一种函数, 用function和声明的代码class都返回一个函数 [[Prototype]]。使用原型,任何函数都可以使用new关键字成为构造函数实例。为了通俗易懂,我们先看几个简单的例子。
const x = function() {};
consot result = new x();
console.log(result);
// x {}
const y = class{};
const res = new y();
console.log(res);
// y {}
定义一个类
构造器js
function Cat(name) {
this.name = name;
}
我们转换为类语法,我们可以看到他的结构非常相似
class Cat {
constructor(name) {
this.name = name;
}
}
定义一个方法
构造器js
function Hero(name, level) {
this.name = name;
this.level = level;
}
// Adding a method to the constructor
Hero.prototype.greet = function() {
return `${this.name} says hello.`;
}
对于类,语法得到了简化
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
greet() {
return `${this.name} says hello.`;
}
}
我们看看,调用结果
cosnt hello = new Hero('zz', 12)
// Output
Hero {name: "zz", level: 12}
__proto__:
▶ constructor: class Hero
▶ greet: ƒ greet()
类的扩展
构造函数的优点和类都有一个共同的优点,
function Mage(name, level, spell) {
Hero.call(this, name, level);
this.spell = spell;
}
const hero2 = new Mage('Lejon', 2, 'Magic Missile');
//打印
Mage {name: "Lejon", level: 2, spell: "Magic Missile"}
__proto__:
▶ constructor: ƒ Mage(name, level, spell)
对于 ES6 类,super关键字用于代替call访问父函数。我们将使用extends来引用父类。
class Mage extends Hero {
constructor(name, level, spell) {
super(name, level);
this.spell = spell;
}
}
const hero2 = new Mage('Lejon', 2, 'Magic Missile');
// 打印
Mage {name: "Lejon", level: 2, spell: "Magic Missile"}
__proto__: Hero
▶ constructor: class Mage
下面并排对比了一个构造函数和一个类的初始化、添加方法、继承的整个过程。 构造器js
function Hero(name, level) {
this.name = name;
this.level = level;
}
Hero.prototype.greet = function() {
return `${this.name} says hello.`;
}
function Mage(name, level, spell) {
Hero.call(this, name, level);
this.spell = spell;
}
类js
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
greet() {
return `${this.name} says hello.`;
}
}
class Mage extends Hero {
constructor(name, level, spell) {
super(name, level);
this.spell = spell;
}
}