JavaScript 对象构造函数

JavaScript 对象构造函数是用来构造对象的函数,与普通函数差不多,区别在于可以通过 new 关键字生成实例的函数就是构造函数,直接调用的就是普通函数。

JavaScript 对象构造函数是用来构造对象的函数,与普通函数差不多,区别在于可以通过 new 关键字生成实例的函数就是构造函数,直接调用的就是普通函数。

为了规范,一般将构造函数的首字母大写。

如下是一个构造函数的示例:

function Person(firstName, lastName, age, eyeColor) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.eyeColor = eyeColor;
}

对象类型/类

前面几章中的对象的例子,只是创建了单个对象。而有时候,我们需要同一个”类型“的多个对象实例,而使用构造函数可以定义对象的类型。

构造函数就是定义了一个对象类型的模版,也相当于其他语言中的 类 的概念。

正如在上面的例子中,function Person() 是一个对象构造函数,他定义了一个类型 Person。

通过使用 new 关键字调用构造函数来创建相同类型的对象:

const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

this 关键字

在 JavaScript 中,对象中的 this 指向的是对象本身,这需要在运行时才能确定具体是哪个对象。

比如上面例子中的 myFathermyMother 两个对象, 当使用 myFather 对象时, this 就是指 myFather,当使用 myMother 对象时,this 就是指 myMother

向对象添加属性

向现有对象添加新属性很容易:

myFather.nationality = "English";

这仅将属性将添加到 myFather,没有添加到 myMother 对象。

向对象添加方法

向现有对象添加新方法很容易:

myFather.name = function () {
  return this.firstName + " " + this.lastName;
};

这仅将方法将添加到 myFather,没有添加到 myMother 对象。

向构造函数添加属性

要给构造函数添加新的属性,必须在构造函数的内部,通过 this 关键字进行添加。

要将新属性添加到构造函数,必须将其添加到构造函数:

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.nationality = "English";
}

这样对象属性就可以有默认值。 将属性添加到构造函数后,所有的对象实例都拥有此属性。

向构造函数添加方法

您的构造函数还可以定义方法:

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.name = function () {
    return this.firstName + " " + this.lastName;
  };
}

将方法添加到构造函数后,所有的对象实例都拥有此方法。

JavaScript 内置的构造函数

JavaScript 具有用于原生对象的内置构造函数:

String(); // 字符串
Number(); // 数字
Boolean(); // 布尔值
Object(); // 对象
Array(); // 数组
RegExp(); // 正则表达式
Function(); // 函数
Date(); // 日期

通过对象的 constructor 属性可以获取对象的构造函数。

"".constructor  // function String()
(1).constructor // function Number()
true.constructor // function Boolean()
{}.constructor // function Object()
[].constructor // function Array()
/a/.constructor // function RegExp()
new Date().constructor // function Date()
(function(){}).constructor // function Function()

使用字面量赋值数据

正如你可以在上面看到,JavaScript 有基本数据类型的对象版本 StringNumberBoolean,但是仍然建议使用字面量赋值变量,避免复杂化。

使用字面量创建各种数据:

  • 使用字符串字面量 "" 而不是 new String().
  • 使用数字字面量 50 代替 new Number().
  • 使用布尔字面量 true / false 而不是 new Boolean().
  • 使用对象字面量 {} 而不是 new Object().
  • 使用数组字面量 [] 代替 new Array().
  • 使用正则字面量 /()/ 而不是 new RegExp().
  • 使用函数表达式 () {} 而不是 new Function().
let x1 = ""; // 字符串
let x2 = 0; // 数字
let x3 = false; // 布尔值
const x4 = {}; // 对象
const x5 = []; // 数组
const x6 = /()/; // 正则表达式
const x7 = function () {}; // 函数