js中面向對象編程

一、使用面向對象的方式來作這個案例---注意:面向對象是面向過程的封裝,不是徹底替代了面向過程 面向對象與,面向過程的區別 ①面向過程就是親力親爲,事無鉅細,步步緊跟 ②面向對象就是找一個對象,指揮獲得結果 ③面向對象將執行者變爲指揮者 ④面向對象不是面向過程的替代,而是面向過程的封裝數組

案例一:隨機生成小方塊  思考:一、這個案例裏能夠抽象出哪些對象---方塊對象bash

    二、隨機生成顏色 位置 ----- 生成隨機數--封裝成函數,可是封裝成函數比較散爲了方便管理,把不一樣功能的函數封裝不一樣對象的方法中app

因此這個項目會有2個對象 方塊對象 + 工具對象 (封裝不少功能函數)dom

   方塊對象有不少,這些對象都很相似,因此咱們能夠經過構造函數的方式來建立對象:批量建立類似類型的對象。函數

   工具對象在整個項目中只有一個,因此直接用建立普通對象的方式來建立工具對象就行。 代碼實現:工具

一、建立工具對象---對象的方法來封裝些功能(生成隨機數) 二、建立方塊對象 a、建立構造函數ui

  b、分析方塊對象的成員---即構造函數的屬性、方法(無對錯,只有合適不合適):   屬性:方塊的背景顏色、方塊的大小、方塊的座標、   方法:隨機生成本身的座標this

function Box(parent, options) {
        options = options || {};
        //設置對象的屬性
        this.backgroundColor = options.backgroundColor || 'red';
        this.width = options.width || 20;
        this.height = options.height || 20;
        this.x = options.x || 0;
        this.y = options.y || 0;
        //建立對應的div 用this.div爲了可以在原型中訪問到這個div
        this.div = document.createElement('div');
        parent.appenChild(div);
    }
    //初始化div的樣式
    Box.prototype.init = function() {
        var div = this.div
        div.style.backgroundColor = this.backgroundColor;
        div.style.width = this.width + 'px';
        div.style.height = this.height + 'px';
        div.style.left = this.x + 'px';
        div.style.top = this.y + 'px';
        //脫離文檔流
        div.style.position = 'absolute'
        //建立對應的div
        this.div = document.createElement('div');
        parent.appendChild(this.div);
        //設置div的樣式
        this.init();
    }
    //隨機生成方塊的位置
    Box.prototype.random = function() {
        //父容器的寬度 方塊的寬度 總共能放多少塊
        var x = Tools.getRandom(0, this.parent.offsetWidth / this.width - 1) * this.width;
        var y = Tools.getRandom(0, this.parent.offsetHeight / this.height - 1) * this.height;
        this.div.style.left = x + 'px';
        this.div.style.top = y + 'px';
    }

複製代碼

三、隨機生成方塊的調用---實現隨機生成方塊spa

//生成十個方塊 隨機生成顏色
	
	//獲取容器
	var container = doucment.getElementById('container');
	for(var i = 0; i < 10; i++) {
		var r = Tools.getRandom(0,255);
		var g = Tools.getRandom(0,255);
		var b = Tools.getRandom(0,255);
		
		var box = new Box(container, {
		backgroundColor: `rgb('+r+','+g+','+b+')`
		});
	}
	//數組 存儲建立的方塊對象
	var array = [];
	for(var i = 0; i < 10; i++) {
		var r = Tools.getRandom(0,255);
		var g = Tools.getRandom(0,255);
		var b = Tools.getRandom(0,255);
		
		var box = new Box(container, {
		backgroundColor: `rgb('+r+','+g+','+b+')`
		});
		array.push(box)
	}
	
	//設置隨機位置開啓定時器
	setInterval(function(){
		//隨機生成方塊的座標
		
	},500);
	setInterval(randomBox, 500);
	
	function randomBox() {
		//隨機生成方塊的座標
		for(var i = 0; i < 10; i++) {
			var box = array[i];
			box.random();
		}
	}
	//設置隨機位置 開啓定時器
	setInterval(randomBox, 500)
	//加載完成 先設置隨機位置
	//用有名函數時爲了頁面一加載時就能夠調用randombox函數不用等500ms避免方塊一開始都在00位置
	function randomBox() {
		for(var i = 0; i < 10; i++) {
			var box = array[i];
			box.random();
		}
	}
複製代碼
相關文章
相關標籤/搜索