- Object.create()
Object.prototype._create = function(obj) {
if(Object.prototype.toString.call(obj) !== '[object Object]') return
let newObj = {}
newObj.__prop__ = obj
return newObj
}
- map
Array.prototype._map = function(fn) = {
if(typeof fn !== 'function') return
let newArr = []
for(var i=0;i<this.length;i++) {
newArr.push(fn(this[i]))
}
return newArr
}
- filter
Array.prototype._filter = function(fn) = {
if(typeof fn !== 'function') return
let newArr = []
for(var i=0;i<this.length;i++) {
if(fn(this[i])) {
newArr.push(this[i])
}
}
return newArr
}
- reduce
Array.prototype._reduce = function(fn, init) = {
if(typeof fn !== 'function') return
let preVal = 0
if(init) {
preVal = init
}
let newArr = []
for(var i=0;i<this.length;i++) {
preVal = fn(preVal, this[i])
}
return preVal
}
- call
Function.prototype._call = function(target = window, ...args) {
target.fn = this
let result = target.fn(...args)
delete target.fn
return result
}
- bind
Function.prototype._bind = function(target,...args1) {
let fn = this
return function(...args2) {
return fn.call(target, ...args1, ...args2)
}
}
fn.getVal._bind(this, 1)(2, 3)
- Object.freeze() - 冻结对象(不可删除/改写/新增属性)
Object.prototype._objectFreeze = function(object) => {
if(Object.prototype.toString.call(object) !== '[object Object]') return
Object.keys(object).forEach(item => {
Object.defineProperty(object, item, {
configurable: false,
enumerable: true,
writable: false
})
})
Object.seal(object);
}
- 浅拷贝
const _shallowClone = (target) => {
if(typeof target === 'object && object !== null) {
const constructor = target.constructor
if(/^(Function|RegExp|Date|Map|Set)$/i).test(constructor.name)) return target
let cloneObj = Array.isArray(target) ? [] : {}
for(prop in target) {
cloneObj[prop] = target[prop]
}
return cloneObj
}else {
return target
}
}
- 寄生组合式继承
function Human(name) {
this.name = name
this.kingdom = 'animal'
this.color = ['yellow', 'white', 'brown', 'black']
}
Human.prototype.getName = function() {
return this.name
}
function Chinese(name,age) {
Human.call(this, name)
this.color = 'yellow'
this.age = age
}
Chinese.prototype = Object.create(Human.prototype)
Chinese.prototype.constructor = Chinese
Chinese.prototype.getAge = function() {
return this.age
}
- 发布订阅模式
class EventEmitter {
constructor() {
this.events = {}
}
on(event, fn) {
if(!this.events[event]) {
this.events[event] = [fn]
}else {
this.events[event].push(fn)
}
}
emit(event, ...args) {
if(this.events[event]) {
this.events[event].forEach(callback => callback(...args))
}
}
}