js创建类的方法

一 、函数构造器:

通过构造函数创建类,使用 function 关键字定义一个函数,并在该函数中定义属性和方法。通过 new 关键字实例化对象。

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
    };
}

var person1 = new Person("Alice", 30);
person1.sayHello(); // Output: Hello, my name is Alice and I am 30 years old.

二、原型链继承:

通过修改原型链来实现类的继承。

// 定义 Person 类
function Person(name, age) {
    this.name = name;
    this.age = age;
}

// 在 Person 原型上添加方法
Person.prototype.introduce = function() {
    return "Hello, my name is " + this.name + " and I am " + this.age + " years old.";
}

// 定义 Student 类,继承自 Person
function Student(name, age, grade) {
    Person.call(this, name, age); // 调用父类构造函数
    this.grade = grade;
}

// 设置 Student 的原型为一个新的 Person 实例
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student; // 修正构造函数指向

// 在 Student 原型上添加额外的方法
Student.prototype.study = function() {
    return this.name + " is studying in grade " + this.grade + ".";
}

// 创建 Person 实例
var person1 = new Person("John", 25);
console.log(person1.introduce()); // 输出 "Hello, my name is John and I am 25 years old."

// 创建 Student 实例
var student1 = new Student("Alice", 20, 12);
console.log(student1.introduce()); // 输出 "Hello, my name is Alice and I am 20 years old."
console.log(student1.study()); // 输出 "Alice is studying in grade 12."

三、ES6 类:

使用 ES6 引入的类语法创建类,使用 class 关键字定义类,并使用 constructor 方法定义构造函数,以及其他方法。

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    sayHello() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

const person1 = new Person("Charlie", 20);
person1.sayHello(); // Output: Hello, my name is Charlie and I am 20 years old.```

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值