Javascript学习摘抄,学会面向对象编程

 构造函数与目标实例化

// 构造函数
function Person(firstName, lastName, dob){
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = new Date(dob);   //Date函数为日期专用函数,可以直接调用 
    this.getBirthYear = function(){
        return this.dob.getFullYear( );
    }
    this.getFullName = function(){
        return `${this.firstName} ${this.lastName}`; 
    }
}

//目标实例化
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');

console.log(person1);
console.log(person2.getFullName())

 ES5中的面对对象编程,下面例子是给原型添加方法。

//原型讲解,面对对象编程
function Person(firstName, lastName, dob){
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = new Date(dob);   //Date函数为日期专用函数,可以直接调用 
}

//查询Person函数中的原型,这里的getBirthYear和getFullYear 均被放置于原型中。
//比较与上一种写法的区别。
//放入原型,对象原型添加方法,每个实例对象里都会添加此方法,节省内存空间。
Person.prototype.getBirthYear = function(){
    return this.dob.getFullYear( );
}
Person.prototype.getFullName = function(){
    return `${this.firstName} ${this.lastName}`; 
}

//目标实例化
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');

console.log(person1);
console.log(person2.getFullName())

ES6中JS 新加了class类,下面例子是给类添加方法。

效果和给原型添加方法一样,方法getBirthYear和getFullName被添加到了原型中

// ES6中JS 新加了class类
//效果和添加原型一样,方法getBirthYear和getFullName被添加到了原型中
class Person {
    constructor(firstName, lastName, dob){      //类中的函数叫方法
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = new Date(dob);
    }

getBirthYear(){         //添加新的方法getBirthYear
    return this.dob.getfullyear();
}

getFullName(){         //添加新的方法getFullName
    return `${this.firstName} ${this.lastName}`; 
}
}
 
//目标实例化
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');

console.log(person1);
console.log(person2.getFullName())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值