- 原型模式是一个创建型的模式
- 创建基类的时候,简单差异化的属性放在构造函数中,消耗资源相同的共嗯那个放在基类原型中
对象都是由函数创建,函数也是对象,so,万物皆对象,so easy !!!想哭。
let obj = {name:'aaa'}
//是下列代码的语法糖:
let obj = new Object();
obj.name = 'aaa'
- 每个函数都有一个属性 叫 prototype
- prototype的属性值是一个对象,默认的只有一个叫做construcor的属性,指向这个函数本身
- 每个对象都有一个隐藏的属性__proto__,这个属性引用了该对象所属类的prototype
- 自定义函数的prototype是有Object创建,所以它的proto指向的就是Object.prototype
- Object.prototype的__proto__指向的是null
instanceof
- instanceof运算符的第一个变量是一个对象,暂时称为A,第二个变量一般是一个函数,暂时称为B
- instanceof的判断规则是:沿着A的__proto__这条线来找,同时沿着B的prototype这条线来找,如果两条线能找到同一个引用,即同一个对象,那么就返回true。如果找到终点还未重合,则返回false。
console.log(Object instanceof Function) //true
console.log(Function instanceof Object) //true
console.log(Function instanceof Function) //true
原型链
- 访问一个对象的属性时,先在基本属性中查找,如果没有,再沿着proto这条链向上找,这就是原型链
- hasOwnPropertyk可以区分一个属性到底是自己的还是从原型中找到
原型优势
- 可以随意扩展
- 可以重写继承的方法
<canvas id="canvas" width="1000" height="600"></canvas>
<script>
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);
}
function getRandomColor(){
let rand = Math.floor(Math.random()*0xFFFFFFF).toString(16);
//let rand = Math.floor(Math.random()*16777215).toString(16);等效写法
if(rand.length == 6){
return "#"+rand;
}else {
return getRandomColor()
}
}
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();
}
canvas.onmousemove = function(event){
new Circle(event.clientX,event.clientY,50)
}
setInterval(function(){
ctx.clearRect(0,0,1000,600)
circles.forEach((circle)=>{circle.update() && circle.render()});
},13)
</script>