1. 类的定义:
class MyClass {
constructor(name) {
// 构造函数,在创建对象时调用
this.name = name;
}
// 类的方法
sayHello() {
console.log(`Hello, ${this.name}!`);
}
}
2. 类的实例化:
const myInstance = new MyClass("John");
myInstance.sayHello(); // 输出: Hello, John!
3. 类的继承:
class MySubClass extends MyClass {
constructor(name, age) {
// 调用父类的构造函数
super(name);
this.age = age;
}
// 子类的方法
sayAge() {
console.log(`${this.name} is ${this.age} years old.`);
}
}
const mySubInstance = new MySubClass("Alice", 25);
mySubInstance.sayHello(); // 输出: Hello, Alice!
mySubInstance.sayAge(); // 输出: Alice is 25 years old.
4. 静态方法和静态属性:
class MyStaticClass {
static staticMethod() {
console.log("This is a static method.");
}
static staticProperty = "Static property value";
}
MyStaticClass.staticMethod(); // 输出: This is a static method.
console.log(MyStaticClass.staticProperty); // 输出: Static property value
5. getter 和 setter:
class GetterSetterExample {
constructor() {
this._value = 0;
}
get value() {
return this._value;
}
set value(newValue) {
if (newValue >= 0) {
this._value = newValue;
} else {
console.log("Value must be non-negative.");
}
}
}
const example = new GetterSetterExample();
console.log(example.value); // 输出: 0
example.value = 42;
console.log(example.value); // 输出: 42
example.value = -1; // 输出: Value must be non-negative.
ES6 Class 提供了更直观的面向对象编程方式,使得代码更易读、易维护,并且支持更丰富的面向对象特性,如继承、静态方法、getter 和 setter 等。
转载请注明出处:http://www.zyzy.cn/article/detail/4681/ES6