Javascript入门速成课4 面向对象OOP

//构造函数(constructor function)
//两种实现方法:原型(prototype)、ES6的类(class)

//构造函数首字母要大写

function Person(firstName, lastName, dob){
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = new Date(dob);
}
Person.prototype.getBirthYear = function(){
    return this.dob.getFullYear();
}
Person.prototype.getFullName = function(){
    return `${this.firstName}.${this.lastName}`;
}

//实例化对象Instantiate object

const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Marry', 'Smith', '5-5-1978');
console.log(person1);
console.log(person2.getFullName());
console.log(person2.getBirthYear());//1978 Date中的自带

/**console.log(person1);

  • 调试器输出:
    Person {firstName: 'John', lastName: 'Doe', dob: Thu Apr 03 1980 00:00:00 GMT+0800 (中国标准时间)}
    dob: Thu Apr 03 1980 00:00:00 GMT+0800 (中国标准时间) {}
    firstName: "John"
    lastName: "Doe"
    [[Prototype]]: Object
    getBirthYear: ƒ ()
    getFullName: ƒ ()
    constructor: ƒ Person(firstName, lastName, dob)
    [[Prototype]]: Object
    */

//类方法实现对象:

class Student {
    //类中的方法叫做constructor
    constructor(firstName, lastName, dob){
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = new Date(dob);
    }

    getBirthYear(){
        return this.dob.getFullYear();
    }

    getFullName(){
        return `${firstName}.${lastName}`
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.HTML DOM (Document Object Model) document.getElementByI...
    廖马儿阅读 1,450评论 0 17
  • javascript代码必须位于 与 中脚本可被放置于 或 中单引号双引号均可双斜杠 // 或 /* ......
    Tdithyrambus阅读 185评论 0 1
  • javascript代码必须位于 与 中脚本可被放置于 或 中单引号双引号均可双斜杠 // 或 /* ......
    Tdithyrambus阅读 183评论 0 0
  • 目录: 1.什么是标准库 2.Object对象及其实例 3.Number对象及其实例 4.string对象及其对象...
    love2013阅读 571评论 0 0
  • 构造函数 构造函数是专门用来生成对象的函数。它提供模板,描述对象的基本结构。 一个构造函数,可以生成多个对象,这些...
    联旺阅读 216评论 0 0