跳转到内容
新建笔记

面向对象编程

JavaScript以原型链实现属性继承,ES6 class提供类与实例语法;对照对象创建、构造函数、共享方法和extends。

(1)创建对象

以下先用对象和构造函数展示原型,再与现代class语法对照;不是说JavaScript没有类。各节完整代码块在独立作用域运行;标为续接的片段依赖相邻构造函数示例。

// 原型对象:
let Student = {
name: 'Robot',
height: 1.2,
run: function () {
console.log(this.name + ' is running...');
}
};
function createStudent(name) {
// 基于Student原型创建一个新对象:
let s = Object.create(Student);
// 初始化新对象:
s.name = name;
return s;
}
let xiaoming = createStudent('小明');
xiaoming.run(); // 小明 is running...
Object.getPrototypeOf(xiaoming) === Student; // true

普通属性读取先查自身,再沿原型链查找,直到原型为null;未找到则返回undefined。原型可为null,例如Object.create(null)不经过Object.prototype。此处说明普通数据属性,不涵盖getter或Proxy等自定义读取行为。

let arr = [1, 2, 3];

image-20240810233955795

Array.prototype定义了indexOf()、shift()等方法,因此你可以在所有的Array对象上直接调用这些方法。函数也是一个对象,

function foo() {
return 0;
}

image-20240810234239313

由于Function.prototype定义了apply()等方法,因此,通常的函数可以继承apply();属性遮蔽或手动改原型会改变查找结果。较长原型链可能增加查找成本,但引擎缓存和优化也会影响性能,不据链长保证具体耗时。

(2)构造函数

除了直接用{ ... }创建一个对象外,JavaScript还可以用一种构造函数的方法来创建对象。它的用法是,先定义一个构造函数,一个普通函数,但是可以用关键字new来调用这个函数,并返回一个对象:

function Student(name) {
this.name = name;
this.hello = function () {
alert('Hello, ' + this.name + '!');
}
}
let xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!

image-20240810234933792

此Student漏写new时是普通调用:非严格经典脚本中this可能落到全局对象并污染全局,严格模式中this为undefined,赋值即抛错。用new时this指向新对象,未显式返回对象则返回新对象;构造函数显式返回另一个对象会替换该结果。箭头函数不能用new,class构造函数反而必须用new。

用new Student()创建的对象还从原型上获得了一个constructor属性,它指向函数Student本身:

// 续接上一Student构造函数与xiaoming实例
xiaoming.constructor === Student.prototype.constructor; // true
Student.prototype.constructor === Student; // true
Object.getPrototypeOf(xiaoming) === Student.prototype; // true
xiaoming instanceof Student; // true

image-20240810235102412

红色箭头是原型链。注意,Student.prototype指向的对象就是xiaoming、xiaohong的原型对象,这个原型对象自己还有个属性constructor,指向Student函数本身。另外,函数Student恰好有个属性prototype指向xiaoming、xiaohong的原型对象,但是xiaoming、xiaohong这些实例通常没有自身prototype属性;用Object.getPrototypeOf读取内部原型。旧图中的__proto__是遗留访问器,不应作为新代码首选,也不适用于所有对象。现在我们就认为xiaoming、xiaohong这些对象“继承”自Student。

// 续接本节Student构造函数(hello为自身属性)
let xiaohong = new Student('小红');
xiaoming.name; // '小明'
xiaohong.name; // '小红'
xiaoming.hello; // function: Student.hello()
xiaohong.hello; // function: Student.hello()
xiaoming.hello === xiaohong.hello; // false

xiaoming和xiaohong各自的name不同,这是对的,否则我们无法区分谁是谁了。

xiaoming和xiaohong各自的hello是一个函数,但它们是两个不同的函数,虽然函数名称和代码都是相同的!

如果我们通过new Student()创建了很多对象,这些对象的hello函数实际上只需要共享同一个函数就可以了,这样可以节省很多内存。

要让创建的对象共享一个hello函数,根据对象的属性查找原则,我们只要把hello函数移动到xiaoming、xiaohong这些对象共同的原型上就可以了,也就是Student.prototype:

image-20240810235518185

function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
const xiaoming = new Student('小明');
const xiaohong = new Student('小红');
xiaoming.hello === xiaohong.hello; // true
Object.hasOwn(xiaoming, 'hello'); // false

调用构造函数千万不要忘记写new。为了区分普通函数和构造函数,按照约定,构造函数首字母应当大写,而普通函数首字母应当小写,这样,一些语法检查工具如jslint将可以帮你检测到漏写的new。

(3)原型继承

在传统的基于Class的语言如Java、C++中,继承的本质是扩展一个已有的Class,并生成新的Subclass。由于这类语言严格区分类和实例,继承实际上是类型的扩展。JavaScript可用class extends;下面保留class普及前的函数桥接写法,以解释原型关系,最后再与class对照。

function Student(props = {}) {
this.name = props.name ?? 'Unnamed';
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
// 正确的继承原型链是: new PrimaryStudent() --> PrimaryStudent.prototype --> Student.prototype --> Object.prototype --> null
// 可借助一个中间对象来实现正确的原型链,这个中间对象的原型要指向Student.prototype。中间对象可以用一个空函数F来实现:
// PrimaryStudent构造函数:
function PrimaryStudent(props = {}) {
Student.call(this, props);
this.grade = props.grade ?? 1;
}
// 空函数F:
function F() {
}
// 把F的原型指向Student.prototype:
F.prototype = Student.prototype;
// 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype:
PrimaryStudent.prototype = new F();
// 把PrimaryStudent原型的构造函数修复为PrimaryStudent:
Object.defineProperty(PrimaryStudent.prototype, 'constructor', {
value: PrimaryStudent, writable: true, configurable: true
});
// 继续在PrimaryStudent原型(就是new F()对象)上定义方法:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
// 创建xiaoming:
let xiaoming = new PrimaryStudent({
name: '小明',
grade: 2
});
xiaoming.name; // '小明'
xiaoming.grade; // 2
// 验证原型:
Object.getPrototypeOf(xiaoming) === PrimaryStudent.prototype; // true
Object.getPrototypeOf(Object.getPrototypeOf(xiaoming)) === Student.prototype; // true
// 验证继承关系:
xiaoming instanceof PrimaryStudent; // true
xiaoming instanceof Student; // true

image-20240811000418273

函数F仅用于桥接,我们仅创建了一个new F()实例,而且,没有改变原有的Student定义的原型链。如果把继承这个动作用一个inherits()函数封装起来,还可以隐藏F的定义,并简化代码:

function inherits(Child, Parent) {
let F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Object.defineProperty(Child.prototype, 'constructor', {
value: Child, writable: true, configurable: true
});
}
// 这个inherits()函数可以复用:
function Student(props = {}) {
this.name = props.name ?? 'Unnamed';
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
function PrimaryStudent(props = {}) {
Student.call(this, props);
this.grade = props.grade ?? 1;
}
// 实现原型继承链:
inherits(PrimaryStudent, Student);
// 绑定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};

桥接也可用Child.prototype = Object.create(Parent.prototype)再定义constructor,避免临时F。该inherits只建立实例原型链,不复制静态属性或建立构造函数自身的继承链。默认值使用??,因此保留空字符串及grade为0;constructor只是普通可修改属性,不能当可靠类型鉴定。

(4)class继承

JavaScript的对象模型是基于原型实现的,特点是简单,缺点是理解起来比传统的类-实例模型要困难,最大的缺点是继承的实现需要编写大量代码,并且需要正确实现原型链。新的关键字class从ES6开始正式被引入到JavaScript中。class的目的就是让定义类更简单。

// 独立的函数对照,改名避免与下方class重复声明
function StudentFunction(name) {
this.name = name;
}
StudentFunction.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
// 如果用新的class关键字来编写Student,可以这样写:
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
// class的定义包含了构造函数constructor和定义在原型对象上的函数hello()(注意没有function关键字),这样就避免了Student.prototype.hello = function () {...}这样分散的代码。
let xiaoming = new Student('小明');
xiaoming.hello();
// extends负责设置原型关系,但仍需理解实例/静态成员及super:
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 记得用super调用父类的构造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}

注意PrimaryStudent的定义也是class关键字实现的,而extends则表示原型链对象来自Student。子类的构造函数可能会与父类不太相同,例如,PrimaryStudent需要name和grade两个参数,并且需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化。

class方法默认不可枚举且在严格模式运行;类不能像普通函数一样直接调用。派生构造函数通常应先super(…)再使用this;本例super负责初始化name。extends同时建立实例原型链及构造函数之间的链,与上面的简化inherits不完全相同。

参考核对:原型链与class。