欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JS中面向对象举例——矩形类及其实例化

程序员文章站 2022-04-24 15:21:46
...

知识点

  1. prototype
    在prototype中添加类/对象的属性或者方法

运行效果

JS中面向对象举例——矩形类及其实例化

代码

<!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 || {};
            //父标签id
            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>
相关标签: Web开发