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>