6、高阶函数
<script>
let arr = [2, 3, 4, 5, 6]
console.log(arr.map((item) => { return 2 * item }))
console.log('******************')
console.log(arr.reduce((a, b) => { return a + b }))
console.log(arr.reduce((a, b) => { return a * b }))
console.log(arr.reduce((a, b) => { return a - b }))
console.log(arr.reduce((a, b) => { return a + b }, 10))
console.log(arr.reduce((a, b) => { return a * b }, 10))
console.log(arr.reduce((a, b) => { return a - b }, 10))
console.log([10, 20, 1, 2].sort());
console.log([10, 20, 1, 2].sort((a, b) => {
return a - b;
}))
console.log([10, 20, 1, 2].sort((a, b) => {
return b - a;
}))
console.log(arr.some((item) => {
return item > 5;
}))
console.log(arr.every((item) => {
console.log(item)
return item < 7
}))
console.log(arr.find(item => {
console.log(item)
return item > 4
}))
console.log('**********')
console.log(arr.findIndex(item => {
return item > 4
}))
</script>
7、重写call
<script>
Function.prototype.myCall = function (params) {
let context = params || window;
context.fn = this;
const args = [];
for (let i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
let result = eval('context.fn(' + args + ')')
delete context.fn;
return result;
}
const say = function (a, b) {
console.log(this)
console.log(a, b)
}
say.myCall({ a: 'qer', b: 'sdfd', name: 'nihaoa' }, 4, 5)
</script>
Function.prototype.myCall = function (params, ...args) {
let context = params || window;
context.fn = this;
let result = context.fn(...args);
delete context.fn;
return result;
}
8、重写apply
<script>
Function.prototype.myApply = function (obj, arr) {
let context = obj || window;
context.fn = this;
debugger
let result;
if (!arr) {
result = context.fn();
} else {
let args = [];
for (let i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn(' + args + ')')
}
delete context.fn;
return result;
}
const say = function (a, b) {
console.log(this)
console.log(a, b)
}
say.myApply({ a: 'qer', b: 'sdfd', name: 'nihaoa' }, [4, 7])
</script>
9、重写instanceof
<script>
const _instanceof = (target, Fn) => {
if ((typeof target !== 'object' || typeof target !== 'function') || target == null)
return false
let proto = target.__proto__
while (true) {
if (proto === null) return false
if (proto === Fn.prototype) return true
proto = proto.__proto__
}
}
function A() { }
const a = new A()
console.log(_instanceof(a, A))
console.log(_instanceof(1, A))
</script>
10、原型链继承
<script>
function Animal() {
this.colors = ['red', 'pink'];
}
Animal.prototype.getColor = function () {
return this.colors;
}
function Dog() { }
Dog.prototype = new Animal()
let dog1 = new Dog()
dog1.colors.push('brown')
let dog2 = new Dog()
console.log(dog2.colors)
</script>