【亡羊补牢】JS灵魂之问 第16期 修炼内功 对象和构造函数区别是什么?

引言

有几天没有更新JS灵魂之问的专栏系列文章了,秋招季,也在忙着备战笔试面试。今天得空再来写一篇文章,本篇要讲解的内容是关于 对象和构造函数基础 ,那今天这篇看能不能问倒你了,一起来探索一下吧。

仰望星空的人,不应该被嘲笑

对象基础

对象前置知识

/* 对象基础知识 */

var teacher = {
    
    
  name: '张三',
  age: 32,
  sex: 'male',
  height: 176,
  weight: 130,
  teach: function(){
    
    
    console.log('I am teaching JS');
  },
  smoke: function(){
    
    
    console.log('I am smoking');
  },
  eat: function(){
    
    
    console.log('I am having a dinner');
  }
}
/* 查找 */
console.log(teacher.name);
teacher.teach();
teacher.smoke();
teacher.eat();

/* 增加 */
teacher.address = '北京'
teacher.drink = function(){
    
    
  console.log('I am drinking beer');
}
console.log(teacher.address);
teacher.drink();

/* 修改 */
teacher.teach = function(){
    
    
  console.log('I am teaching Vue');
}
teacher.teach();

/* 删除 */
delete teacher.address;
delete teacher.teach;
console.log(teacher);

构造函数基础

从上文我们可以知道,创建对象的一种方式,通过 {} (即对象字面量)来创建。下面我们来讲讲采用构造函数方式创建。

第一种,通过系统自带的构造函数

var obj = new Object();
obj.name = '张三';
obj.sex = '男士';
console.log(obj);

这种方式通过系统自带的构造函数实例化出来的,其实是和对象字面量一样,没啥区别。

对象和构造函数不能混淆,对象是通过实例化构造函数而创建的。这里不知道小伙伴们理不理解,下文会探讨这个问题的。

第二种,自定义构造函数

对于自定义构造函数,我们一般采用大驼峰命名(单词首字母全大写),里面一个关键词 this,考一考,此时 this 指向谁?指向 Teacher吗?

/* 自定义构造函数 采用大驼峰命名*/
function Teacher(){
    
    
  this.name = '张三';
  this.sex = '男士';
  this.smoke = function(){
    
    
    console.log('I am smoking')
  }
}

答案是 this 根本不存在,因为函数在 GO里面,里面内容根本不会看,如下:

GO = {
    
    
	Teacher: function(){
    
    ...}
}

因此 this都没有生成,并且 Teacher是构造函数。而如果想要 this存在,就需要实例化,因为上文提到的,this它是指向的对象本身。因此,需要如下一行代码,进行实例化操作。

var teacher = new Teacher();

好的,那么我们现在对上述代码进行一丢丢修改,看下面代码会打印什么?

function Teacher(){
    
    
  this.name = '张三';
  this.sex = '男士';
  this.smoke = function(){
    
    
    console.log('I am smoking')
  }
}

var teacher1 = new Teacher();
var teacher2 = new Teacher();

teacher1.name = '李四';
console.log(teacher1.name);
console.log(teacher2.name);

答案是 李四 张三。因为通过构造函数 new 出来的两个对象根本不是一个东西,是两个不同的对象,因此更改某一个完全不影响另外一个对象。也就是说构造函数实例化的多个对象相互之间是不影响的。

下面给出一份封装构造函数的基础代码:

function Teacher(opt){
    
    
  this.name = opt.name;
  this.sex = opt.sex;
  this.weight = opt.weight;
  this.course = opt.course;
  this.smoke = function(){
    
    
    this.weight--;
    console.log(this.weight);
  }
  this.eat = function(){
    
    
    this.weight++;
    console.log(this.weight);
  }
}

var t1 = new Teacher({
    
    
  name: '张三',
  sex: '男士',
  weight: 130,
  course: 'JS'
});
var t2 = new Teacher({
    
    
  name: '李四',
  sex: '女士',
  weight: 90,
  course: 'Vue'
});
console.log(t1);
console.log(t2);

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小狮子前端の笔记仓库

访问超逸の博客,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/108650024
今日推荐