一. 构造函数
1. js内置构造函数
String 、Number 、 Boolean 、 Array 、Object 、Date 、Function ...
构造函数的命名规范 名称首字母大写。
2. 构造函数
构造函数是一种用于构建对象的代码块。由new操作符调用。
new 操作符可以做什么? 可以创建空对象,并且调用函数的时候把这个对象返回。
// 示例:
1) 普通函数
function Apple(c, addr) {
// 数据挂在window对象下
this.color = c;
this.address = addr;
console.log(this);// window 对象
}
Apple("红色","山东");
// 2) 构造函数
var _this ;// _this 这是普通变量
function Apple(c, addr) {
// 数据挂在window对象下
this.color = c;
this.address = addr;
console.log(this);// Apple {} 对象
// this 内置的指针变量
_this = this;
}
// new Apple("红色","山东") 这行代码执行完就可以得到实例对象
// 那么a1就是用于记录实例对象的变量
var a1 = new Apple("红色","山东");//创建实例
console.log(a1 === _this);// true 由此可知,this指向构造函数创建的实例对象
3. 总结:
构造函数是用于构建、设计对象的函数,需要使用new来调用
普通函数作用域的this,往往指向window。因为其在全局环境下
构造函数作用域的this,指向构造函数所创建的实例,因为它是由new来调用
this 是指针变量。不同的作用域this指向是不同。
二. 两个构造函数的案例
1.生成随机大小和颜色的圆
代码演示
function Draw(color, size, x, y) {
this.color = color;
this.size = size;
this.x = x;
this.y = y;
}
Draw.prototype.drawCircle = function () {
document.write(`<div style='
width: ${this.size}px;
height: ${this.size}px;
border-radius: 50%;
background-color: ${this.color};
position: absolute;
top: ${this.y}px;
left: ${this.x}px;
'></div>`);
};
for (let i = 0; i < 50; i++) {
let color = getRandomColor();
let size = getRandomSize();
let position = getRandomPosition();
let { x, y } = position;
let circle = new Draw(`${color}`, size, x, y);
circle.drawCircle();
}
2. 构造函数思想生成随机彩票
<script>
/* 创建生成二维数组的构造函数 */
function myArray(col, row) {
this.col = col;
this.row = row;
this.getArr = function () {
let arr = new Array(this.col);
for (let i = 0; i < this.col; i++) {
arr[i] = new Array(this.row);
for (let j = 0; j < this.row; j++) {
if (j == this.row - 1) {
arr[i][j] = getRandomBlue();
} else {
arr[i][j] = getRandomRed();
}
}
}
return arr;
};
}
/* 调用并获取二维数组 */
let getArray = new myArray(10, 7);
let arrData = getArray.getArr();
// console.log(arrData);
/* 渲染加工 */
for (let i = 0; i < arrData.length; i++) {
document.write(`<div class='box'>`);
for (let j = 0; j < arrData[i].length; j++) {
j === arrData[i].length - 1
? document.write(`<div class='blue'>${arrData[i][j]}</div>`)
: document.write(`<div class='red'>${arrData[i][j]}</div>`);
}
document.write(`</div>`);
}
//随机数函数 0 ~ 33
function getRandomRed() {
let arr = [];
for (let i = 0; i < 33; i++) {
arr.push(i);
}
let random = Math.floor(Math.random() * (arr.length - 1) + 1);
return arr.splice(random, 1)[0];
}
function getRandomBlue() {
return Math.floor(Math.random() * 16 + 1);
}
</script>
我在第二个案例的实现思路为动态生成一个二维数组,元素为随机数,再通过两次循环进行结构渲染。getArr方法可以挂载到构造函数的原型对象身上,进行优化。