关键词

JS优雅的使用function实现一个class

使用function实现一个class的过程被称为JavaScript中的“类式继承”。下面是一个完整攻略,包含了步骤和示例。

步骤

  1. 使用function定义一个主要的类,并将它赋值给一个变量,例如Person。这个类将包含构造函数和其他的原型方法。
  2. 在主类中定义原型方法,例如Person.prototype.sayHello,这里是一个例子:

    javascript
    Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name);
    }

  3. 创建子类,使其继承主类。可以使用call()来调用父类构造函数。例如:

    javascript
    function Student(name, grade) {
    Person.call(this, name);
    this.grade = grade;
    }

  4. 使用Object.create()将子类的原型链设置为父类的实例。例如:

    javascript
    Student.prototype = Object.create(Person.prototype);

  5. 重写子类的构造函数(因为它现在指向了父类的构造函数),并添加新的子类原型方法。例如:

    ```javascript
    Student.prototype.constructor = Student;

    Student.prototype.study = function() {
    console.log("I'm studying in grade " + this.grade);
    }
    ```

  6. 创建子类的实例并使用它们。例如:

    ```javascript
    var person = new Person("Alice");
    person.sayHello(); // 输出 "Hello, my name is Alice"

    var student = new Student("Bob", 5);
    student.sayHello(); // 输出 "Hello, my name is Bob"
    student.study(); // 输出 "I'm studying in grade 5"
    ```

示例

下面是两个使用function实现类的示例。

示例1:Animal类和Bird子类

function Animal(name) {
    this.name = name;
}

Animal.prototype.eat = function(food) {
    console.log(this.name + " is eating " + food);
}

function Bird(name, wingspan) {
    Animal.call(this, name);
    this.wingspan = wingspan;
}

Bird.prototype = Object.create(Animal.prototype);

Bird.prototype.constructor = Bird;

Bird.prototype.fly = function() {
    console.log(this.name + " is flying with wingspan " + this.wingspan);
}

var animal = new Animal("Tiger");
animal.eat("meat");  // 输出 "Tiger is eating meat"

var bird = new Bird("Eagle", 2.5);
bird.eat("fish");    // 输出 "Eagle is eating fish"
bird.fly();           // 输出 "Eagle is flying with wingspan 2.5"

示例2:Person类和Teacher子类

function Person(name) {
    this.name = name;
}

Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name);
}

function Teacher(name, subject) {
    Person.call(this, name);
    this.subject = subject;
}

Teacher.prototype = Object.create(Person.prototype);

Teacher.prototype.constructor = Teacher;

Teacher.prototype.teach = function() {
    console.log(this.name + " is teaching " + this.subject);
}

var person = new Person("Alice");
person.sayHello();   // 输出 "Hello, my name is Alice"

var teacher = new Teacher("Bob", "Math");
teacher.sayHello();  // 输出 "Hello, my name is Bob"
teacher.teach();     // 输出 "Bob is teaching Math"

本文链接:http://task.lmcjl.com/news/10959.html

展开阅读全文