第二十七课:原型和原型链
学习目标:
- 理解原型(
prototype
)的概念。 - 理解原型链的工作原理。
- 掌握如何通过原型链判断对象的类型。
- 学习类的原型和原型链。
- 理解如何使用原型链继承属性和方法。
学习内容:
1. 原型(prototype
)的概念:
-
每个JavaScript函数都有一个
prototype
属性,这个属性是一个指向原型对象的指针。当你使用构造器创建一个新对象时,这个对象内部的[[Prototype]]
链接到构造函数的prototype
对象上。代码示例:
function Person(name) { this.name = name; } var person1 = new Person('Alice');
预计输出效果:
Person.prototype
是person1
的原型。person1
可以访问Person.prototype
上定义的属性和方法。
2. 原型链的工作原理:
-
原型链是JavaScript中实现继承的主要机制。每个对象都有一个指向其原型对象的链,并且这个原型对象也有自己的原型,以此类推,直到一个对象的原型是
null
。代码示例:
console.log(person1.__proto__ === Person.prototype); // true console.log(Person.prototype.__proto__ === Object.prototype); // true console.log(Object.prototype.__proto__); // null
3. 通过原型链判断对象的类型:
-
可以使用
instanceof
运算符和Object.prototype.isPrototypeOf()
方法来判断对象是否是某个构造函数的实例。代码示例:
console.log(person1 instanceof Person); // true console.log(Person.prototype.isPrototypeOf(person1)); // true
4. 类的原型和原型链:
-
在ES6之后,JavaScript提供了
class
关键字来创建类,但在底层仍然使用原型链。代码示例:
class Person { constructor(name) { this.name = name; } greet() { return `Hello, my name is ${this.name}`; } } const person2 = new Person('Bob'); console.log(person2.greet()); // "Hello, my name is Bob"
预计输出效果:
person2
继承自Person
类。Person.prototype
中的greet
方法可以被person2
调用。
5. 使用原型链继承属性和方法:
-
通过设置对象的原型到另一个对象的
prototype
,可以实现继承。代码示例:
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { return this.name + ' makes a noise.'; }; function Dog(name) { Animal.call(this, name); // 调用父类的构造函数 } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.bark = function() { return this.name + ' barks.'; }; var dog = new Dog('Rex'); console.log(dog.speak()); // "Rex makes a noise." console.log(dog.bark()); // "Rex barks."
课后练习:
- 创建一个
Shape
构造函数,包含type
属性,并且定义一个getType()
方法。 - 创建一个
Triangle
构造函数,继承Shape
,并且增加一个sideLength
属性。 - 创建一个
Triangle
的对象,调用getType()
方法,确保原型链工作正常。 - 使用
instanceof
检查创建的对象是否是Triangle
和Shape
的实例。
练习解析:
-
Shape
和getType()
定义:function Shape(type) { this.type = type; } Shape.prototype.getType = function() { return this.type; };
-
Triangle
继承Shape
,增加sideLength
:function Triangle(sideLength) { Shape.call(this, 'triangle'); this.sideLength = sideLength; } Triangle.prototype = Object.create(Shape.prototype); Triangle.prototype.constructor = Triangle;
-
创建
Triangle
对象,调用方法:var triangle = new Triangle(3); console.log(triangle.getType()); // "triangle"
-
检查实例:
console.log(triangle instanceof Triangle); // true console.log(triangle instanceof Shape); // true
通过这些练习,你将更好地理解原型和原型链的工作方式以及如何在JavaScript中实现继承。