写部分js原生方法

131 阅读1分钟

1、数组的map方法

Array.prototype.myMap = function (fn, thisArg) {
	let array = this
	let newArray = []
	for (let key = 0; key < array.length; key++) {
		newArray.push(fn.apply(thisArg, [array[key], key]))
	}
	return newArray
}
let obj = {
	xixi: 122,
}
let c = [1, 2, 3].myMap(function (item, index) {
	return item * 10 + '-' + this.xixi
}, obj)

2、数组的reduce方法

Array.prototype.myReduce = function (callBack, initialValue) {
	let src = this
	let initV = initialValue
	for (let key = 0; key < src.length; key++) {
		initV = callBack(initV, src[key], key, src)
	}
	return initV
}
let reduceResult = [1, 2, 3, 4].myReduce((acc, cur, idx, src) => {
	acc[`aa-${idx}`] = cur
	return acc
}, {})

3、new 关键字的实现


function create() {
	let obj = {}
        let args = Array.from(arguments)
	let fn = args.shift()
	obj.__proto__ = fn.prototype
	let res = fn.apply(obj, arguments) //改变this指向,为实例添加方法和属性
	return typeof res === 'object' ? res : obj
}
function Person(name, age) {
	this.name = name
	this.age = age
}
Person.prototype.sayHi = function () {
	console.log(`你好${this.name}`)
}
let p2 = create(Person, '李四', 19)
p2.sayHi()

4、手写call、apply

Function.prototype.myCall = function (context) {
	let _this = context || window
	_this.fn = this
	let args = Array.from(arguments)
	let result = _this.fn(...args.slice(1))
	delete _this.fn
	return result
}
Function.prototype.myApply = function (context, arr) {
	let _this = context || window
	_this.fn = this
	let result = _this.fn(...arr)
	delete _this.fn
	return result
}