Posted on 

构造函数

基础概念

使用场景:需要重复创建很多类似的对象。

关键词: new

语法:

  1. 技术上是常规函数。
  2. 两点约定:
    1. 命名以大写字母开头,如User 。
    2. 只能以new 操作符来执行。

主要目的: 实现可重用的对象创建代码。

引例

1
2
3
4
5
6
7
8
9
10
function User(name) { 
this.name = name;
this.isAdmin = false;
}

let user = new User("Jack");

alert(user.name); // Jack

alert(user.isAdmin); // false

当例子中的函数被new 操作符执行时:

  1. 一个this 对象被创建。
  2. this 对象添加属性。
  3. 返回this 对象的值。

即等同于:

1
2
3
4
let user = {
name = "Jack",
isAdmin = false
}

用法

由于构造函数在技术上和普通函数没有区别,因此任何函数都可以被用作构造器,都可以通过new 来运行。

new function()用法

如果我们有许多行用于创建单个复杂对象的代码,我们可以将它们封装在构造函数中——旨在封装单个对象的代码,之后不再也无法重用。

1
2
3
4
let user = new function() { 
this.name = "John";
this.isAdmin = false;
};

构造器的return

通常构造器没有return 语句:构造器的任务是将属性写入对象this ,并返回值。

如果构造器有return :只有返回对象时覆盖this ,否则忽略。

构造器中的方法

this 中不仅可以添加属性,也可以添加方法。

1
2
3
4
5
6
7
8
9
10
function User(name) { 
this.name = name;
this.sayHi = function() {
alert( "My name is: " + this.name );
};
}

let john = new User("John");

john.sayHi(); // My name is: John

总结

  1. 构造函数(构造器)是一个具有共同约定——首字母大写的常规函数。
  2. 构造器通常不含return 。如果有,只有在返回对象时才有效。
  3. 构造器只能通过new 调用,正如其名,调用在一开始创建一个空白的this , 返回一个含有属性的this 。
  4. JavaScript内置了许多构造函数,如Date , Set 。