js 面向对象


js面向对象

<input type="button" value="显示效果" id="btn">
<div> id="dv" <\div>

function ChangeStyle(btnObj, dvObj, json) {
this.btnObj = btnObj;
this.dvObj = dvObj;
this.json = json;
}
ChangeStyle.prototype.init = function () {
//点击按钮,改变div多个样式属性值
var that = this;
this.btnObj.onclick = function () {//按钮
  for (var key in that.json) {
    that.dvObj.style[key] = that.json[key];
    console.log(that.dvObj.style)
   };
  };
};

//实例化对象

var json = {"width": "500px", "height": "800px", "backgroundColor": "blue", "opacity": "0.2"};
var cs = new ChangeStyle(document.getElementById("btn"), document.getElementById("dv"), json);
cs.init();//调用方法

//点击p标签,设置div的样式

//点击按钮,改变div的背景颜色

//  document.getElementById("btn").onclick=function () {
      document.getElementById("dv").style.backgroundColor="yellow";
  };

//面向对象思想----初级的
//按钮是一个对象,div是一个对象,颜色是一个属性


  function ChangeStyle(btnId,dvId,color) {
    this.btnObj=document.getElementById(btnId);//按钮对象
    this.dvObj=document.getElementById(dvId);//div对象
    this.color=color;//颜色
  }
  //数据共享来改变背景颜色
  ChangeStyle.prototype.init=function () {
    //console.log(this);//就是实例对象---就是当前对象
    var that=this;
    //点击按钮,改变div的背景颜色
    this.btnObj.onclick=function () {
      that.dvObj.style.backgroundColor=that.color;
    };
  };

//实例化对象
  var cs=new ChangeStyle("btn","dv","yellow");
 cs.init();


  function Person() {
    this.sayHi=function () {
      console.log(this);
    };
  }
  var p=new Person();
  p.sayHi();