zoukankan      html  css  js  c++  java
  • JavaScript 域名学习及对象的继承实现

    1.定义命名空间

     var Namespace = new Object(); 
      Namespace.register = function(path){ 
        var arr = path.split("."); 
        var ns = ""; 
        for(var i=0;i<arr.length;i++){ 
          if(i>0) ns += "."; 
          ns += arr[i]; 
          eval("if(typeof(" + ns + ") == 'undefined') " + ns + " = new Object();"); 
        } 
      } 

    1.定义一个Goods类

    (function(){

     //注册命名空间 com.turing   
     Namespace.register("com.turing");
     
     //定义类
     com.turing.Goods = function(){

      this.name="Goods";
      
      this.getContext = function(){
       //第一步:获取canvas元素
       var canvasDom = document.getElementById("demoCanvas");
       //第二步:获取上下文
       return canvasDom.getContext('2d');
      }

      this.paint = function(){
      
       this.getContext().strokeStyle = "red";
       //第四步:绘制矩形,只有线。内容是空的
       this.getContext().strokeRect(10, 10, 190, 100);
       //设置字体样式
       this.getContext().font = "30px Courier New";
       this.getContext().fillText( this.name , 50, 50);
       
      }
     }
     
    })();

    2.定义一个子类继承Goods类,并覆盖paint方法。

    (function(){

     //注册命名空间 com.turing   
     Namespace.register("com.turing");
     
     //定义类
     com.turing.Apple = function(){
      
     }
     //继承
     com.turing.Apple.prototype = new com.turing.Goods();
     
     //扩展(属性)
     com.turing.Apple.prototype.name = "Apple";

     //扩展(方法)
     com.turing.Apple.prototype.paint = function(){

      this.getContext().strokeStyle = "blue";
      this.getContext().beginPath();
      this.getContext().arc(10+80,10+40,50,0,Math.PI*2,true); //Math.PI*2是JS计算方法,是圆
      this.getContext().stroke();
      //this.getContext().strokeRect(10, 10, 190, 100);
      
      //设置字体样式
      this.getContext().font = "30px Courier New";
      this.getContext().fillText( this.name , 50, 50);
     }
    })();

    3.使用方法

    <html>
    <head>
     
     <script src="Namespace.js"></script>
     <script src="Goods.js"></script>
     <script src="Apple.js"></script>
     
    </head>
    <body>

    <canvas id="demoCanvas" width="500" height="500">

    <script>

     
     var a = new com.turing.Apple();
     a.paint();

    </script>
    </body>
    </html>

  • 相关阅读:
    Android 9.png图片制作
    Android 基于Socket的聊天室
    poj 1659 Frogs' Neighborhood
    zoj 2836 Number Puzzle
    zoj 1372 Networking
    hdoj 4259 Double Dealing
    Direct2D (33) : 通过 ID2D1BitmapRenderTarget 绘制背景网格
    Direct2D (36) : RenderTarget.DrawText() 与 IDWriteTextFormat
    Direct2D (35) : 通过 DirectWrite 获取字体列表
    Direct2D (37) : 使用不同画刷绘制文本
  • 原文地址:https://www.cnblogs.com/scote/p/4800063.html
Copyright © 2011-2022 走看看