# promise 封装
ajax
function getJSON(url) {
let promise = new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onreadystatechange = function() {
if (this.readyState !== 4) return
if (this.readyState === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
xhr.onerror = function() {
reject(new Error(this.statusText))
}
xhr.responseType = 'json'
xhr.setRequestHeader('Accept', 'application/json')
xhr.send(null)
return promise
})
}
# 构造函数的写法
es5
function Person(firstName, lastName, age, address) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.address = address
}
Person.self = function () {
return this
}
Person.prototype.toString = function() {
return '[object Person]'
}
Person.prototype.getFullName = function() {
return this.firstName + '' + this.lastName
}
es6
class Person {
constructor(firstName, lastName, age, address) {
this.lastName = lastName
this.firstName = firstName
this.age = age
this.address = address
}
static self () {
return this
}
toString() {
return 'object Person'
}
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
# 封装一个通用事件的侦听函数
const EventUtils = {
// 视能力分别使用dom0 || dom2 || IE方式来绑定事件
// 添加事件
addEvent: function(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false)
} else if (element.attachEvent) {
element.attachEvent('on'+type, handler)
} else {
element['on'+ type] = handler
}
},
// 移除事件
removeEvent: function(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false)
} else if (element.detachEvent) {
element.detachEvent('on' +type, handler)
} else {
element['on'+type] = null
}
},
// 获取事件目标
getTarget: function(event) {
return event.target || event.srcElement
},
// 获取event对象的引用,获取事件的所有信息,确保随时能使用event
getEvent: function(event) {
return event | window.event
},
// 阻止事件(主要是事件冒泡,因为iE不支持事件捕获)
stopPropagation: function(event) {
if (event.stopPropagation) {
event.stopPropagation()
} else {
event.cancelBubble = true
}
},
// 取消事件的默认行为
preventDefault: function(event) {
if (event.preventDefault) {
event.preventDefault()
} else {
event.returnValue = false
}
}
}
← promise.md 数组方法.md →