JavaScript中的构造函数的使用
function Person(name,age){
this.name = name;
this.age = age;
this.showID = function (){
console.log("My name is " + this.name);
console.log("I'm " + this.age +" years old");
}
}
let Ulrich = new Person('Ulrich',22);
Ulrich.showID();
也可以把构造函数中的showID给分离出来,方便多个不同的构造函数的使用
function Person(name,age){
this.name = name;
this.age = age;
this.showID = fun;
}
function fun(){
console.log("My name is " + this.name);
console.log("I'm " + this.age +" years old");
}
let Ulrich = new Person('Ulrich',22);
Ulrich.showID();
输出结果:
prototype的使用
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.showID = function () {
console.log("My name is " + this.name);
console.log("I'm " + this.age +" years old");
console.log("------")
}
let Ulrich = new Person('Ulrich',22);
let Odd = new Person('Odd',17);
Ulrich.showID();
Odd.showID();
相当于在类中添加一个方法,让所有对象都可以共享使用