<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oop编程增强版写法——js面向对象编程实例</title>
</head>
<body>
<div id="container" style="border:3px solid red;width:400px;height:400px;"></div>
</body>
<script type="text/javascript">
//Java学科基类
var Java = function(content){
//将文本内容保存在属性content里
this.content = content;
//创建对象时,通过自调用函数直接执行
(function(content){//自调用函数的形参content
var div = document.createElement('div');
div.innerHTML = content;
div.style.color = 'green';
div.style.width = 200+'px';
div.style.height = 200+'px';
div.style.background = 'white';
div.style.border = '1px solid olive';
// alert(div.style.background);
//获取父容器container(注:这里获取DOM元素必须在DOM建立形成之后获取,否则报错),并将div添加到container中
document.getElementById('container').appendChild(div);
})(content);//自调用函数的实参content
}
//php学科基类
var Php = function(content){
this.content = content;
(function(content){
var div = document.createElement('div');
div.innerHTML = content;
div.style.color = 'green';
div.style.width = 200+'px';
div.style.height = 200+'px';
div.style.background = 'white';
div.style.border = '1px solid olive';
document.getElementById('container').appendChild(div);
})(content);
}
//Javascript学科基类
var Javascript = function(content){
this.content = content;
(function(content){
var div = document.createElement('div');
div.innerHTML = content;
div.style.color = 'green';
div.style.width = 200+'px';
div.style.height = 200+'px';
div.style.background = 'white';
div.style.border = '1px solid olive';
document.getElementById('container').appendChild(div);
})(content);
}
//UI学科基类
var Ui = function(content){
this.content = content;
(function(content){
var div = document.createElement('div');
div.innerHTML = content;
div.style.color = 'green';
div.style.width = 200+'px';
div.style.height = 200+'px';
div.style.background = 'white';
div.style.border = '1px solid olive';
document.getElementById('container').appendChild(div);
})(content);
}
//学科工厂类
var JobFactory = function(type,content){
switch(type){
case 'java':
return new Java(content);
case 'php':
return new Php(content);
case 'js':
return new Javascript(content);
case 'ui':
return new Ui(content);
}
}
//测试用例
var java = JobFactory('java','java是门后台语言');
console.log(java);
console.log(java.content);
var php = JobFactory('php','php是门后台语言');
console.log(php);
console.log(php.content);
var js = JobFactory('js','js是前端web开发语言');
console.log(js);
console.log(js.content);
var ui = JobFactory('ui','ui交互设计');
console.log(ui);
console.log(ui.content);
//本例已经通过验证
</script>
</html>