這是一個 用 面向?qū)ο髞?創(chuàng)建對象 的典型的列子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用面向?qū)ο髣?chuàng)建矩形</title>
</head>
<body>
<div class="box" id="box">
</div>
<script>
window.onload = function () {
//1. 創(chuàng)建構(gòu)造函數(shù)(創(chuàng)建類)
//要把屬性也放在原型庫中,使用一個初始化方法 _init
function Rect(option){
//然后在構(gòu)造函數(shù)中調(diào)用初始化方法, 同時也把這個初始化方法放在原型庫中,
//初始化方法是用來初始化屬性的
this._init(option);
}
// 2. 給原型屬性擴展方法和初始化屬性 (原型庫的寫法)
Rect.prototype = {//注意 名字的第一個字要大寫
_init:function(option){
//優(yōu)化:就是使用json把參數(shù)保存起來,直接傳遞json
var option = option || {};
//設(shè)置屬性
//2.1 放在哪里
this.parentId = option.parentId;
//2.2 設(shè)置位置
this.left = option.left ||100;
this.top = option.top ||100;
//2.3 設(shè)置大小
this.width = option.width||100;
this.height = option.height||50;
//設(shè)置其他
this.backgroundColor = option.backgroundColor||'blue';
this.border = option.border||0;
this.borderRadius = option.borderRadius||10;
},
//繪制方法
render: function () {
// 1.獲取 parent 標(biāo)簽
var parentNode = document.getElementById(this.parentId);
//創(chuàng)建 div
var childNode = document.createElement('div');
//2.設(shè)置標(biāo)簽的相關(guān)屬性
parentNode.style.position = 'relative';//給父標(biāo)簽 設(shè)置 relative
childNode.style.position = 'absolute';
childNode.style.left = this.left + 'px';//設(shè)置位置 左邊的多少
childNode.style.top = this.top + 'px';
childNode.style.width = this.width + 'px'; //設(shè)置對象的寬度
childNode.style.height = this.height + 'px';
//設(shè)置其他
childNode.style.backgroundColor = this.backgroundColor;
childNode.style.border = this.border;
childNode.style.borderRadius = this.borderRadius + 'px';
//添加
parentNode.appendChild(childNode);
}
}
//如果要進行封裝也是可以的,直接把上面的全部放在js文件夾中
//創(chuàng)建新的矩形
var mrRect = new Rect({
parentId:'box',
left:200,
top:200,
width:500,
height:300,
backgroundColor:'yellow',
border:'10px solid red',
borderRadius:15
});
//繪制,調(diào)用方法
mrRect.render();
}
</script>
</body>
</html>