9.1.1、构造函数,对象,类和实例定义
1.构造函数:构造一个类的函数
2.对象:某一类事物的具体实例
3.类:对某一具体事物的抽象
4.实例:new出来的对象
9.1.2、构造函数的特点
1.首字母大写
2.函数内部使用this关键字,谁new(实例化)就指向谁
3.使用this关键字给对象添加属性
4.必须使用new关键字,去生成一个对象
// 在 javascript 中新建一个类 使用构造函数
function Student(name,age){
this.name = name;
this.age=age
}
/* this 指实例化的对象 */
/* 实例 */
var zheng = new Student("zcy",18)
console.log(zheng);
// 读取对象的属性
console.log(p.name);
console.log(p.age);
9.1.3、构造函数的缺点
同一个构造函数的多个实例之间,无法共享属性,从而造成对系统资源的浪费。
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.eat = "水果"
var p = new Person("li",19)
var zhang = new Person("zhang",20)
console.log(p);
console.log(zhang);
9.1.4、instanceof
判断一个对象是不是某个类的实例
var arr = [1,2,3]
console.log(arr instanceof Array); // true
function Person(name,age){
this.name = name
this.age = age
}
var p = new Person("zheng",18)
console.log(p instanceof Person); // true