创建基类的时候,简单差异化的属性放在构造函数中,消耗资源相同的功能放在基类原型中;
使用场景:
- 降低 实例对象 个数,减少 构造函数 的调用次数;
优点:
- 性能高:使用 原型模式复用 的方式 创建实例对象,比使用构造函数重新创建对象 性能要高; ( 针对类实例对象开销大的情况 )
- 流程简单:原型模式可以 简化创建的过程,可以直接修改现有的对象实例的值,达到 复用 的目的; ( 针对构造函数繁琐的情况 )
缺点:
- 深拷贝 与 浅拷贝 风险:克隆对象时进行的一些修改,容易出错; 需要灵活运用 深拷贝 与 浅拷贝操作;
类图
bad
function Person(name) {
this.name = name;
// 每次实例化都会开辟一个新的内存空间
this.getName = function () {
console.log(this.name);
}
}
let p1 = new Person('张三');
let p2 = new Person('李四');
console.log(p1.getName === p2.getName); // false
good
function Person(name) {
this.name = name;
}
// 放在原型上,只会开辟一个内存空间,可以复用
Person.prototype.getName = function () {
console.log(this.name);
}
let p1 = new Person('张三');
let p2 = new Person('李四');
console.log(p1.getName === p2.getName); // true
场景(canvas)
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="600"></canvas>
<script>
//随机颜色,十六进制方法;
function getRandomColor() {
var rand = Math.floor(Math.random() * 0xFFFFFF).toString(16);
if (rand.length == 6) {
return '#' + rand;
}
return getRandomColor();
}
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let circles = [];
function Circle(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
circles.push(this);
}
Circle.prototype.update = function () {
this.radius--;
if (this.radius > 0) {
return true;
}
}
Circle.prototype.render = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = getRandomColor();
ctx.fill();
}
let circle = new Circle(0, 0, 30);
canvas.onmousemove = function (event) {
circles.push(new Circle(event.clientX, event.clientY, 30));
}
setInterval(function () {
ctx.clearRect(0, 0, 1000, 600);
circles.forEach(item => {
item.update() && item.render();
});
circles = circles.filter(item => item.radius > 0);
}, 20);
</script>
</body>
</html>
效果
打赏作者
您的打赏是我前进的动力
微信
支付宝
策略模式
上一篇
评论