构造函数与目标实例化
// 构造函数
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())