1. Defining namespaces
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. Define a goods class
(function () {
Register namespace Com.turing
Namespace.register ("com.turing");
Defining classes
Com.turing.Goods = function () {
This.name= "Goods";
This.getcontext = function () {
First step: Get the canvas element
var canvasdom = document.getElementById ("Democanvas");
Step Two: Get context
Return Canvasdom.getcontext (' 2d ');
}
This.paint = function () {
This.getcontext (). Strokestyle = "Red";
Fourth step: Draw the rectangle, only the line. The content is empty
This.getcontext (). Strokerect (10, 10, 190, 100);
Set font style
This.getcontext (). Font = "30px Courier New";
This.getcontext (). Filltext (THIS.name, 50, 50);
}
}
})();
2. Define a subclass to inherit the goods class and overwrite the paint method.
(function () {
Register namespace Com.turing
Namespace.register ("com.turing");
Defining classes
Com.turing.Apple = function () {
}
Inherited
Com.turing.Apple.prototype = new Com.turing.Goods ();
Extensions (properties)
Com.turing.Apple.prototype.name = "Apple";
Extension (method)
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 is the JS calculation method, is the circle
This.getcontext (). stroke ();
This.getcontext (). Strokerect (10, 10, 190, 100);
Set font style
This.getcontext (). Font = "30px Courier New";
This.getcontext (). Filltext (THIS.name, 50, 50);
}
})();
3. How to use
<script src= "Namespace.js" ></script>
<script src= "Goods.js" ></script>
<script src= "Apple.js" ></script>
<body>
<canvas id= "Democanvas" width= "height=" >
<script>
var a = new Com.turing.Apple ();
A.paint ();
</script>
</body>
JavaScript Domain name learning and the implementation of object inheritance