在 JavaScript 中,构造函数有多种不同的方式可以定义和声明,下面是其中八种最常见的方法:1. 基本构造函数定义
```javascript
function Constructor(arg1, arg2) {
this.prop1 = arg1;
this.prop2 = arg2;
}
```
2. 使用函数表达式定义构造函数
```javascript
const Constructor = function(arg1, arg2) {
this.prop1 = arg1;
this.prop2 = arg2;
}
```
3. 箭头函数无法用作构造函数
```javascript
const Constructor = (arg1, arg2) => {
this.prop1 = arg1;
this.prop2 = arg2;
} // 错误
```
4. 使用 class 定义构造函数
```javascript
class Constructor {
constructor(arg1, arg2) {
this.prop1 = arg1;
this.prop2 = arg2;
}
}
```
5. 声明 constructor 属性并使用 this
```javascript
function Constructor(arg1, arg2) {
this.prop1 = arg1;
this.prop2 = arg2;
}
Constructor.prototype.constructor = Constructor;
```
6. 使用 Object.create 和 Object.assign 创建构造函数
```javascript
const BaseConstructor = function() {};
BaseConstructor.prototype.init = function(arg1, arg2) {
this.prop1 = arg1;
this.prop2 = arg2;
};
function Constructor(arg1, arg2) {
BaseConstructor.call(this);
this.init(arg1, arg2);
}
Constructor.prototype = Object.create(BaseConstructor.prototype);
Object.assign(Constructor.prototype, {
constructor: Constructor
});
```
7. 使用 apply 和 arguments 创建构造函数
```javascript
function Constructor() {
const args = Array.prototype.slice.call(arguments);
this.prop1 = args[0];
this.prop2 = args[1];
}
```
8. 使用 ES6 参数默认值
```javascript
function Constructor(arg1 = defaultValue1, arg2 = defaultValue2) {
this.prop1 = arg1;
this.prop2 = arg2;
}
```
这八种方式并不是全部的构造函数定义和声明方法,但是它们是最常见的。您可以根据需要选择最适合的构造函数声明方法。
1.默认构造函数:类名(){}
2.带参数的构造函数:类名(参数列表){}
3.拷贝构造函数:类名(const 类名&){}
4.提供默认值的构造函数:类名(参数列表=默认值){}
5.委托构造函数:类名(参数列表):其他构造函数名(参数列表){}
6.虚拟基类构造函数:类名(参数列表):虚拟基类名(参数列表){}
7.显式构造函数:explicit 类名(){}
8.删除构造函数:类名()=delete;
构造法:在几何图形最为常见,如构造手拉手、一线三角相似(全等)、构造三垂直型全等……,在代数运算或证明中也极为常见。
例1.已知a、b、c为实数,且4a−4b+c>0,a+2b+c<0,请说明b²>ac
分析:设y=ax²+2bx+c(a≠0)
当x=−2时,y=4a−4b+c>0
当x=1时,y=a+2b+c<0
∴方程ax²+2bx+c=0,有两个不同的根
∴△=4b²−4ac>0
∴b²>ac
例2.已知实数a,b分别满足方程1/a²+1/a−3=0和b²+b−3=0,且ab≠1,求(a²b²+1)/a²的值。
分析:两方程对应系数相同,可以构造一元二次方程再运用韦达定理求解
∵ab≠1,∴1/a≠b
令:1/a和b是x²+x−3=0的两个根
∴根据韦达定理:1/a+b=−1,1/a.b=−3
∴(a²b²+1)/a²=b²+1/a²
=(b+1/a)²−2a.1/a
=(−1)²−2×(−3)=7
例3.若b≠0,ab≠1,且有5a²+2021a+9=0及9b²+2021b+5=0,求a/b的值。
分析:可将两方程对应系数化一致,便可构造一元二次方程
∵b≠0
∴将9b²+2021b+5=0两边同时除以b²得
5(1/b)²+2021.(1/b)+9=0
∵ab≠1,即a≠1/b,此时两方程对应系数相同,可以构造一元二次方程
∴令a,1/b是5x²+2021x+9=0两个根
∴根据韦达定理:a.1/b=9/5
即:a/b=9/5。