面向过程和面向对象思想

<style>
    div{
        width: 200px;
        height: 200px;
        background-color: pink;
    }
</style>

//点击更改div的颜色

//面向过程

/* document.getElementById(“btn”).onclick=function () {
document.getElementById(“dv”).style.backgroundColor=“blue”;

}*/

//面向对象
//操作谁:按钮 , div, 颜色
/* function Style(btnId,dv,color) {
this.btnId=document.getElementById(btnId);//按钮对象
this.dvId=document.getElementById(dv);//div对象
this.color=color; //颜色属性

}
//在原型中添加方法
Style.prototype.init=function () {
    //点击改变颜色
    console.log(this);//实例对象
    //函数嵌套时,this指向会发生变化
    var that=this;
    this.btnId.onclick=function () {
        console.log(this);//指向按钮
        //that.dvId.style.backgroundColor="red";
        that.dvId.style.backgroundColor=that.color;
    }
}

//实例化对象
var change=new Style(“btn”,“dv”,“yellow”);
change.init();
console.log(change.color);*/

//需求按下键盘获取文本框的value的值
function Get(txt) {
this.txt=document.getElementById(txt);
}
Get.prototype.init=function () {
var that=this;
console.dir(this);
this.txt.onkeydown=function () {
console.log(that.txt.value);
}
}
var g=new Get(“text”);
g.init();
console.dir(g);
console.dir(Get);

注意:函数嵌套时,this指向会发生变化, var that=this;这里的指向是对象,而在事件里的this指向是按钮元素。从上面可以看出面向过程的代码少些,面向对象思想的代码多些;面向过程是注重过程,面向对象思想是注重结果的。

猜你喜欢

转载自blog.csdn.net/qq_43469418/article/details/86529734