麻烦每行代码带上注释
时间: 2023-06-22 18:26:23 浏览: 34
好的,以下是每行代码带注释的示例:
1. 构造函数继承
```javascript
function Parent(name) { // 定义父构造函数
this.name = name;
}
Parent.prototype.sayName = function() { // 定义父类原型上的方法
console.log(this.name);
}
function Child(name, age) { // 定义子构造函数
Parent.call(this, name); // 调用父构造函数,并传递子构造函数的 this 和 name 参数
this.age = age; // 定义子构造函数自己的属性 age
}
var child = new Child('Tom', 18); // 创建子构造函数的实例
console.log(child.name); // Tom,子构造函数实例继承了父构造函数的属性
console.log(child.age); // 18,子构造函数实例具有自己的属性
```
2. 混合继承
```javascript
function Parent(name) { // 定义父构造函数
this.name = name;
}
Parent.prototype.sayName = function() { // 定义父类原型上的方法
console.log(this.name);
}
function Child(name, age) { // 定义子构造函数
Parent.call(this, name); // 调用父构造函数,并传递子构造函数的 this 和 name 参数
this.age = age; // 定义子构造函数自己的属性 age
}
Child.prototype = new Parent(); // 将子构造函数的原型指向父构造函数的实例
Child.prototype.constructor = Child; // 将子构造函数原型上的 constructor 设置为子构造函数本身
var child = new Child('Tom', 18); // 创建子构造函数的实例
console.log(child.name); // Tom,子构造函数实例继承了父构造函数的属性
console.log(child.age); // 18,子构造函数实例具有自己的属性
child.sayName(); // Tom,子构造函数实例继承了父构造函数的原型上的方法
```
3. ES6 继承
```javascript
class Parent { // 定义父类
constructor(name) { // 定义父类构造函数
this.name = name;
}
sayName() { // 定义父类原型上的方法
console.log(this.name);
}
}
class Child extends Parent { // 定义子类,并继承父类
constructor(name, age) { // 定义子类构造函数
super(name); // 调用父类构造函数,并传递子类构造函数的 name 参数
this.age = age; // 定义子类自己的属性 age
}
}
var child = new Child('Tom', 18); // 创建子类的实例
console.log(child.name); // Tom,子类实例继承了父类的属性
console.log(child.age); // 18,子类实例具有自己的属性
child.sayName(); // Tom,子类实例继承了父类的原型上的方法
```