//构造函数(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}`
}
}