一 ,什么是面向对象
1.首先,js面向对象是一种思想;
2.其次,遵循万物皆对象的准则;程序中的关键模块都可以视为对象,对象都是由属性和方法组成,属性可以理解为对象的特征,是静态的,方法可以理解为对象的行为,是动态的;例如,在汽车这个对象中,他的颜色,型号,大小就是他的属性,而行驶则是他的方法;
3.面向对象会使用对象的属性和方法,它不关注内部的细节和过程;同时也会构造对象。
就像我们说的 一般new 出来的 都是面向对象 比如 new Date() new XMLHttpRequest()等
二,有哪些类型
在es6出来之前
function Div(id) {
}
Div.prototype.init = function () {
// 逻辑
}
Div.prototype.down = function (e) {
//逻辑
}
new Div()
我们看出来 这样非常的繁琐 所以 出来了class类方法
class Div {
constructor(id) {
//声明的对象值
}
init() {
//方法
}
down() {
//方法
}
}
new Div('.div1')
这样看起来非常的简便 更容易理解
三,拖拽方法
function Div(id) {
//初始化我们需要的值
this.divid = document.getElementById(id);
this.divx = 0;
this.divy = 0
this.init()
}
Div.prototype.init = function () {
//初始化的方法
let This = this
this.divid.onmousedown = function (e) {
This.down(e)
return false
}
}
Div.prototype.down = function (e) {
//鼠标点击时候的方法
var This = this
var even = e || window.event
this.divx = even.clientX - this.divid.offsetLeft
this.divy = even.clientY - this.divid.offsetTop
document.onmousemove = function (e) {
//鼠标点击后触发移动的方法
This.move(e)
}
document.onmouseup = function () {
//鼠标松开后触发移动的方法
This.up()
}
}
Div.prototype.move = function (e) {
var even = e || window.event
this.divid.style.left = even.clientX - this.divx + "px"
this.divid.style.top = even.clientY - this.divy + "px"
}
Div.prototype.up = function () {
document.onmousemove = null
document.onmouseup = null
}
new Div('div1')
es6方法
class Div {
constructor(id) {
this.divId = document.querySelector(id)
this.divx = 0
this.divy = 0
this.init()
}
init() {
this.divId.onmousedown = (e) => {
this.down()
}
}
down() {
var e = e || window.event
this.divx = e.clientX - this.divId.offsetLeft
this.divy = e.clientY - this.divId.offsetTop
document.onmousemove = (e) => {
this.move(e)
}
document.onmouseup = () => {
this.up()
}
}
move(e) {
var e = e || window.event
this.divId.style.left = e.clientX - this.divx + 'px'
this.divId.style.top = e.clientY - this.divy + 'px'
}
up(e) {
document.onmouseup = null
document.onmousemove = null
}
}
new Div('.div1')
如果有错误