共计 1861 个字符,预计需要花费 5 分钟才能阅读完成。
JavaScript 分为五个章节,包括 JS 进阶,ES6,Typescript,包管理和自动化打包构建。
1:基本概念
提起构造函数,我们需要从 JS 的创建对象开始,JS 的创建对象有两种方式,一种是对象字面量法(把一个对象的属性和方法一一罗列出来),对象字面量法有一个明显的不足在于它不适合批量的或者是构建大量的类似或者重复的对象,由于这个限制也就有了另一种创建方式,构造函数。
对象字面量
const person = { | |
name: 'Eric', | |
age: 28, | |
school: '侠课岛', | |
getName: function() {return this.name;}, | |
getAge: function() {return this.age;}, | |
}; |
构造函数
function Person(name, age) { | |
this.name = name || ''; | |
this.age = age || 0; | |
school: '侠课岛', | |
this.getName = function() {return this.name;} | |
this.getAge = function() {return this.age} | |
} | |
const Eric = new Person('Eric', 26); |
什么是构造函数?
构造函数是一个构建对象的函数,在创建对象时就初始化对象,为对象成员变量赋予一个初始值,比如上面的 person 函数里面如果没有传 name 和 age 进去,那么默认的 name 的初始值就是空,age 就是 0。它总是与 new 运算符一起使用在创建对象语句中,构造函数最主要的特点在于它方便创建多个对象的实例。
2:构造函数的特点
- 首字母必须大写(区分于普通函数)
- 它的 this 是指向生成的实例对象
- 构造函数需要使用 new 关键字来生成实例对象,如果不是要 new 关键字那么构造函数就和普通函数没有区别了
3:构造函数与普通函数的区别
- 构造函数可以当做普通函数使用,尽可能避免把构造函数当成一个普通函数来使用,因为它不符合软件设计的原则。
- 构造函数内部会创建实例,使用 new 关键字和构造函数结合的时候,会返回一个对象。普通函数不会创建实例,仅仅返回的是 return 的值。
-
构造函数内部的 this 指向实例本身,普通函数指向调用者(不包括箭头函数)。普通函数比如一个函数调用另一个函数,那么在被调用函数内部它的 this 是指向调用者,如果直接去执行这个函数,那么默认的这个调用者就是 window。
/* 构造函数 */ function Person() {console.log('this', this); } const A = new Person(); /* 普通函数 */ function person() {console.log('this', this); } const B = person();
4:构造函数返回值(分三种情况)
-
无 return(void),返回 this(这个 this 指向的就是这个构造函数实例化的对象本身)
function Student(name){this.name = name || '';}
-
return 基本数据类型,返回 this
function Teacher(name){this.name = name || '';} const Davy = new Teacher('Davy'); concole.log(Davy); -
return 对象,返回对象
function Driver(name){ this.name = name; return {name: 'xxx';}; } const Micheal = new Driver('Micheal'); console.log(Micheal);
5:构造函数的构建过程(总共分为四步)
-
创建一个空对象
var obj = {};
-
将空对象的 proto 指向构造函数对象的 prototype,为了方便对象的校验和对象的继承
obj.__proto__ = constructorFunction.prototype;
-
将构造函数的作用域赋给新对象本身
var result = constructorFunction.call(obj);
-
返回新对象,处理返回值,首先要判断 constructorFunction 的执行结果是否是一个 object,如果是,就会返回 return(构造函数内部返回的值),如果不是,则直接返回新创建的值。
typeof result === 'object' ? result : obj; var obj = {}; obj.__proto__ = constructorFunction.prototype; constructorFunction.call(obj); return obj;