ES5构造函数
(构造函数相当于是一张图纸,通过图纸可以构造出想要的实例,而实例间是相互独立的,只是通过同一套模板实现不同的实体)
function Person(name, age) {
//this指向当前对象
this.name = name;
this.age = age;
}
const p1 = new Person("lisa", 20);
const p2 = new Person("luna", 22);
console.log(p2);
结果:
***语法糖:把之前的语法经过包装变为另一种语法
ES6中新增“类”:(仿类结构)
class Person {
constructor(name, age) { //构造函数
this.name = name;
this.age = age;
}
}
console.log(typeof Person)
//结果为:function,实质上与在前写的构造方法是一样 的,只不过把他放到class下
console.log(new Person("lisa", 20));
结果:
在构造函数中使用原型:
function Person(name, age) {
//this指向当前对象
this.name = name;
this.age = age;
}
Person.prototype.eat = function() {
console.log("eat");
}
const p1 = new Person("lisa", 20);
p1.eat(); //先在当前对象中找eat属性,没找到后就到原型中找该属性
//此时,p1或p2指向的都是同一个函数,节省了内存空间
class Person {
constructor(name, age) { //构造函数
this.name = name;
this.age = age;
}
eat() {
console.log("eat");
}
}
const p1 = new Person("Luna", 22);
console.log(p1);
结果: