js继承实例
<html> <head> <script> function Point(x,y){ this.x=x; this.y=y; } function Line(p1,p2){ this.p1 = p1; this.p2 = p2; this.length=Math.sqrt(Math.pow(p1.x - p2.x,2)+ Math.pow(p1.y - p2.y,2)); } function Shape(){ this.points = []; this.lines = []; this.init(); } Shape.prototype={ constructor:Shape, init:function(){ if(this.context === undefined){ var canvas = document.getElementById('canvas'); Shape.prototype.context = canvas.getContext('2d'); //var canvas = document.getElementById('canvas'); //Shape.prototype.context = canvas.getContext('2d'); } }, draw:function(){ var i,ctx=this.context; ctx.strokeStyle = this.getColor(); ctx.beginPath(); ctx.moveTo(this.points[0].x,this.points[0].y); for(i=1;i<this.points.length;i++){ ctx.lineTo(this.points[i].x,this.points[i].y); } ctx.closePath(); ctx.stroke(); }, getColor:function(){ var i,rgb = []; for(i=0;i<3;i++){ rgb[i] = Math.round(255 * Math.random()); } return 'rgb('+rgb.join(',')+')'; }, getLines:function(){ if(this.lines.length > 0){ return this.lines; } var i,lines=[]; for(i=0;i<this.points.length;i++){ lines[i] = new Line(this.points[i], this.points[i+1] || this.points[0]); } this.lines = lines; return lines; }, getArea:function(){}, getPerimeter:function(){ var i,perim = 0,lines = this.getLines(); for(i=0;i<lines.length;i++){ perim += lines[i].length; } return perim; } }; function Triangle(a,b,c){ this.points = [a,b,c]; this.getArea = function(){ var p = this.getPerimeter(); s = p/2; return Math.sqrt(s *(s-this.lines[0].length) *(s-this.lines[1].length) *(s-this.lines[2].length)); } } function Rectangle(p,side_a,side_b){ this.points=[p, new Point(p.x + side_a,p.y), new Point(p.x + side_a,p.y+side_b), new Point(p.x,p.y + side_b)]; this.getArea=function(){ return side_a*side_b; } } function Square(p,side){ Rectangle.call(this,p,side,side); } function myclick(){ var s = new Shape(); Triangle.prototype = s; Rectangle.prototype = s; Square.prototype = s; var p1 = new Point(100,100); var p2 = new Point(300,100); var p3 = new Point(200,0); var t = new Triangle(p1,p2,p3); t.draw(); console.log(t.getPerimeter()); console.log(t.getArea()); var r = new Rectangle(new Point(200,200),50,100); r.draw(); console.log(r.getArea()); console.log(r.getPerimeter()); var s = new Square(new Point(130,130),50); s.draw(); console.log(s.getArea()); console.log(s.getPerimeter()); new Square(p1,200).draw(); } </script> </head> <body> <canvas height="600" width="800" id="canvas" onclick="myclick()"/> </body> </html>
效果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
2012-04-20 table布局中的一些关键点
2012-04-20 如何在标签<a>中跨网页动态获取传递的值