模拟实现自定义类

// 定义构造函数
function Person(name, gender, age) {
    this.name = name;
    this.gender = gender;
    this.age = age;

    this.intro = function () {
        console.log('俺叫%s(%s),今年%d岁。', this.name, this.gender, this.age)
    };
}

let person = new Person('张三', '男', 18);

console.log('姓名:%s', person.name);   // 姓名:张三
console.log('性别:%s', person.gender); // 性别:男
console.log('年龄:%d', person.age);    // 年龄:18

person.intro(); // 俺叫张三(男),今年18岁。

Copyright © 2023 码农人生. All Rights Reserved