知识点
- prototype
在prototype中添加类/对象的属性或者方法
运行效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="main"></div>
<script>
function Rect(option){
this._init(option)
}
Rect.prototype = {
_init :function (option) {
option = option || {};
this.parentId = option.parentId;
this.left = option.left || 0;
this.top = option.top || 0;
this.width = option.width || 100;
this.height = option.height || 50;
this.backgroundColor = option.backgroundColor || 'blue';
this.border = option.border || 0;
this.borderRadius = option.borderRadius || 0;
},
render:function () {
var parentNode = document.getElementById(this.parentId);
var childNode = document.createElement('div');
childNode.style.position = 'absolute';
childNode.style.left = this.left + 'px';
childNode.style.top = this.top + 'px';
childNode.style.width = this.width + 'px';
childNode.style.height = this.height + 'px';
childNode.style.backgroundColor = this.backgroundColor;
childNode.style.border = this.border;
childNode.style.borderRadius = this.borderRadius + 'px';
parentNode.appendChild(childNode);
}
};
var rect = new Rect({
parentId:'main',
left:100,
top:200,
width:300,
height:50,
backgroundColor:'yellow',
border:'10px solid #000',
borderRadius:30
});
var rect1 = new Rect({
parentId:'main',
left:100,
top:500,
width:200,
height:400,
backgroundColor:'red',
border:'10px solid #000',
borderRadius:0
});
rect.render();
rect1.render();
</script>
</body>
</html>