9.1.1、构造函数,对象,类和实例定义

  1. 1.构造函数:构造一个类的函数
  2. 2.对象:某一类事物的具体实例
  3. 3.类:对某一具体事物的抽象
  4. 4.实例:new出来的对象

9.1.2、构造函数的特点

  1. 1.首字母大写
  2. 2.函数内部使用this关键字,谁new(实例化)就指向谁
  3. 3.使用this关键字给对象添加属性
  4. 4.必须使用new关键字,去生成一个对象
  1. // 在 javascript 中新建一个类 使用构造函数
  2. function Student(name,age){
  3. this.name = name;
  4. this.age=age
  5. }
  6. /* this 指实例化的对象 */
  7. /* 实例 */
  8. var zheng = new Student("zcy",18)
  9. console.log(zheng);
  10. // 读取对象的属性
  11. console.log(p.name);
  12. console.log(p.age);

9.1.3、构造函数的缺点

同一个构造函数的多个实例之间,无法共享属性,从而造成对系统资源的浪费。

  1. function Person(name,age){
  2. this.name = name
  3. this.age = age
  4. }
  5. Person.prototype.eat = "水果"
  6. var p = new Person("li",19)
  7. var zhang = new Person("zhang",20)
  8. console.log(p);
  9. console.log(zhang);

9.1.4、instanceof

判断一个对象是不是某个类的实例

  1. var arr = [1,2,3]
  2. console.log(arr instanceof Array); // true
  3. function Person(name,age){
  4. this.name = name
  5. this.age = age
  6. }
  7. var p = new Person("zheng",18)
  8. console.log(p instanceof Person); // true