“面向过程”、“面向对象”,这两个概念总是出现我们身边,那么它们到底什么区别呢?下面通过两段简单的代码,帮助大家理解一下

先写个html

//body
<button id="btn" type="button">点击切换</button>
<div id="box"></div>

//css
div{
    width:200px;
    height:200px;
    background-color:red;
}

我们的目标就是点击按钮,切换div样式,下面开始写JS部分

面向过程写法

document.getElementById("btn").onclick=function(){
    document.getElementById("box").style.backgroundColor="blue";
}

这个大家都好理解,”点击btn,box的background-color变蓝色”,直接翻译,这就是面向过程。

面向对象写法

function Change(btnId,boxId,color){
    this.btn=document.getElementById(btnId);
    this.box=document.getElementById(boxId);
    this.color=color;              //-->per(上面三个this)
};

Change.prototype.init=function(){     //添加函数(即方法)
    var that=this;             //-->per()
    this.btn.onclick=function(){
        //this; //-->per.btn (this不再指向per,而是this.btn)
        that.box.style.backgroundColor=that.color;
    };   
};
var per=new Change("btn","box","blue");
per.init();

这里的难点包括用函数创建对象,以及函数中this的指向.

这就是这两种思维方式的差别体现,从上面可以发现,似乎面向过程写法还简短易懂些,为什么还要求用面向对象的写法呢?

用过框架、插件的朋友看见这个就会有那么一点模糊的感觉了。

上代码:

            function my$(id) {
                return document.getElementById(id);
            }
            function Change(btnId,boxId,json){
                this.btn=btnId;
                this.box=boxId;
                this.json=json;
            };
            Change.prototype.init=function(){
                that=this;
                this.btn.onclick=function(){
                    for(var x in that.json){
                        that.box.style[x] = that.json[x];
                    } 
                };
            };
            var json={"width":"400px","height":"400px","background-color":"blue"};   //使用JSON
            var per=new Change(my$("btn"),my$("box"),json);
            per.init();

当你掌握一定的技巧后,在做大项目时,用面向对象方式的优点就出来了,对于一些同样的处理,可以直接调用函数,不用重复写代码,而且灵活度高。

更多相关文章

  1. 彷徨中的成长-记一个文科生的IT成长过程
  2. [置顶] linux 下安装python cx_Oracle过程详解
  3. 安装:Ubuntu12.04+Python3+Django1.7.9过程记录
  4. python 处理csv文件的过程对换行符的处理
  5. linux centos 宝塔主机控制面板安装和安全狗安装过程记录
  6. 在linux操作系统下,进行j2ee的web开发,是怎么一个过程和体验?
  7. [置顶] linux下Redis服务器部署过程详解
  8. LINUX内核PCI扫描过程
  9. libpcap丢包原理分析及Fedora 9 内核2.6.25.14下安装PF-RING的详

随机推荐

  1. Android的5层平台架构
  2. Android中图片Bitmap的缩放
  3. Android常用布局
  4. android studio 开发android app 真机调
  5. Android(安卓)多个Activity之间的跳转 超
  6. 使用Android Studio查看Android 5.x源码
  7. [Android] Eclipse Android中设置模拟器
  8. android-xml布局属性 - 随心
  9. android之四大组件之一-Activity(三)
  10. Android模拟器及编译环境安装新手入门-3