mirror of
https://github.com/Estom/notes.git
synced 2026-04-05 03:48:56 +08:00
javascript 简单复习
This commit is contained in:
53
JavaScript/ecmascript-5/inherit.md
Normal file
53
JavaScript/ecmascript-5/inherit.md
Normal file
@@ -0,0 +1,53 @@
|
||||
## 原型链
|
||||
|
||||
构造函数或构造器具有 prototype 属性,对象具有 `__proto__` 属性,这就是之前学习的原型。
|
||||
|
||||
如果构造函数或对象 A ,A 的原型指向构造函数或对象 B,B 的原型再指向构造函数或对象 C,以此类推,最终的构造函数或对象的原型指向 Object 的原型。由此形成一条链状结构,被称之为原型链。
|
||||
|
||||
按照上述的描述,在 B 中定义的属性或方法,可以直接在 A 中使用并不需要定义。这就是继承,它允许每个对象来访问其原型链上的任何属性或方法。
|
||||
|
||||
原型链是 ECMAScript 标准中指定的默认实现继承的方式。
|
||||
|
||||
原型链的示意结构图如下:
|
||||
|
||||

|
||||
|
||||
### 原型链实现继承
|
||||
|
||||
```javascript
|
||||
function A(){
|
||||
this.name = "a";
|
||||
this.toString = function(){return this.name};
|
||||
}
|
||||
function B(){
|
||||
this.name = "b";
|
||||
}
|
||||
function C(){
|
||||
this.name = "c";
|
||||
this.age = 18;
|
||||
this.getAge = function(){return this.age};
|
||||
}
|
||||
B.prototype = new A();
|
||||
C.prototype = new B();
|
||||
```
|
||||
|
||||
上述代码实现的示意图如下:
|
||||
|
||||

|
||||
|
||||
### 只继承于原型
|
||||
|
||||
出于对效率的考虑,尽可能地将属性和方法添加到原型上。可以采取以下方式:
|
||||
|
||||
- 不要为继承关系单独创建新对象。
|
||||
- 尽量减少运行时的方法搜索。
|
||||
|
||||
根据上述方式进行更改后,代码如下:
|
||||
|
||||
```javascript
|
||||
function A(){}
|
||||
A.prototype.name = "a";
|
||||
A.prototype.toString = function(){return this.name};
|
||||
|
||||
function B(){}
|
||||
B.prototype = A.prototype;
|
||||
Reference in New Issue
Block a user