1. call 和 apply 的区别是什么,哪个性能更好一些

  1. apply和call 的作用是一样的,区别在于传入参数的不同;
  2. call:第一个参数是为函数内部指定this指向,后续的参数则是函数执行时所需要的参数,一个一个传递。
  3. apply:第一个参数与call相同,为函数内部this指向,而函数的参数,则以数组的形式传递,作为apply第二参数。
  4. call 的性能更好

    记忆方法:call后面的两个 l 是复数,代表参数是散的

  1. /// call源码实现
  2. Function.prototype.call = function (obj, ...arg) {
  3. const context = obj || window;
  4. const fn = Symbol(); // 保证唯一
  5. context[fn] = this; //谁调用这个函数,this就指向谁
  6. const ret = context[fn](...arg);
  7. delete context[fn];
  8. return ret;
  9. }
  10. // apply源码实现
  11. Function.prototype.apply = function(obj, arg) {
  12. const context = obj;
  13. const fn = Symbol();
  14. context[fn] = this;
  15. const ret = context[fn](...arg);
  16. delete context[fn]
  17. return ret;
  18. }

其他 https://github.com/mqyqingfeng/Blog/issues/11

  1. fn.call.call(fn2)//实际执行的是fn2
  2. 相当于 Function.prototype.call.call(fn2)
  3. 相当于 fn2.call() 即为fn2

2. 编写parse函数,实现访问对象里属性的值

  1. let obj = { a: 1, b: { c: 2 }, d: [1, 2, 3], e: [{ f: [4, 5, 6] }] };
  2. let r1 = parse(obj, 'a') // 1
  3. let r2 = parse(obj, 'b.c') // 2
  4. let r3 = parse(obj, 'd[2]') // 3
  5. let r4 = parse(obj, 'e[0].f[0]') // 4
  6. console.log(r1, r2, r3, r4)
  7. // 方法1
  8. function parse (obj, str) {
  9. return new Function('obj', `return obj.${str}`)(obj)
  10. }
  11. // 方法2
  12. function parse (obj, str) {
  13. str = str.replace(/\[(\d+)\]/g, '.$1') //[n] -> .n
  14. const attrs = str.split('.')
  15. attrs.forEach(attr => {
  16. obj = obj[attr]
  17. })
  18. return obj
  1. new Function ([arg1[, arg2[, ...argN]],] functionBody)
  2. // 创建了一个能返回两个参数和的函数
  3. const adder = new Function("a", "b", "return a + b");
  4. // 调用函数
  5. adder(2, 6);
  6. // 8

3.数组扁平化flat方法的多种实现

  1. let arr = [
  2. [1],
  3. [2, 3],
  4. [4, 5, 6, [7, 8, [9, 10, [11]]]],
  5. 12
  6. ]
  1. // 方法1:ES6中 Array.prototype.flat()
  2. console.log(arr.flat(Infinity))
  3. // 方法2:toString
  4. function flat (arr) {
  5. return arr.toString().split(',').map(item => Number(item)) //转成字符串会只有一个逗号相隔
  6. }
  7. console.log(flat(arr))
  8. // 方法3:stringify
  9. function flat (arr) {
  10. let str = JSON.stringify(arr)
  11. str = str.replace(/\[|\]/g, '') //去掉中括号
  12. return str.split(',').map(item => Number(item)))
  13. }
  14. console.log(flat(arr))
  15. // 方法4:concat
  16. function flat (arr) {
  17. while(arr.some(item => Array.isArray(item))) {
  18. arr = [].concat(...arr)
  19. }
  20. return arr
  21. }
  22. console.log(flat(arr))
  23. // 方法5:递归
  24. function flat (arr) {
  25. let result = []
  26. function _loop (arr) {
  27. arr.forEach(item => {
  28. if (Array.isArray(item)) {
  29. _loop(item)
  30. } else {
  31. result.push(item)
  32. }
  33. })
  34. }
  35. _loop(arr)
  36. return result
  37. }

4.实现一个不可变对象

  • 无论是不可扩展,密封,还是冻结,都是浅层控制的,即只控制对象本身属性的增删改。如果对象属性是一个引用类型,比如数组 subArr 或对象 subObj等,虽然subArr、subObj 的不可被删改,但subArr、subObj 的属性仍然可增删改
  • 由于每个对象都有一个属性proto,该属性的值是该对象的原型对象,也是引用类型,由于冻结是浅层的所以原型对象并不会被连着冻结,仍然可以通过给对象的原型对象加属性达到给当前对象新增属性的效果。所以如果想进一步冻结还需要把原型对象也冻结上

    不可扩展

    Object.preventExtensions()可以使一个对象不可再添加新的属性,参数为目标对象,返回修改后的对象 ```javascript var obj = { name: ‘zhufeng’ }; console.log(Object.isExtensible(obj));// true Object.preventExtensions(obj); console.log(Object.isExtensible(obj)); // false

//Object.defineProperty(obj, ‘age’, {value: 10}); //TypeError: Cannot define property age, object is not extensible obj.age = 10; console.log(obj.age); // undefined

  1. <a name="E2cek"></a>
  2. #### 密封
  3. - Object.seal() 可以使一个对象无法添加新属性的同时,也无法删除旧属性。参数是目标对象,返回修改后的对象
  4. - 其本质是通过修改属性的 configurable 为 false 来实现的
  5. - configurable 为 false 时,其他配置不可改变,writable 只能 true 变 false,且属性无法被删除。而由于只要 writable 或 configurable 其中之一为 true,则 value 可改,所以密封之后的对象还是可以改属性值的
  6. - Object.isSealed() 可以检测一个对象是否密封,即是否可以增删属性。参数是目标对象,返回布尔值,true 代表被密封不可增删属性,false 代表没被密封可增删属性
  7. ```javascript
  8. var obj = new Object();
  9. Object.isExtensible(obj); // true
  10. Object.isSealed(obj); // false
  11. Object.seal(obj);
  12. Object.isExtensible(obj); // false,注意 seal 后对象的 isExtensible() 也随之改变
  13. Object.isSealed(obj); // true
  14. var obj = { name: 'zhufeng' };
  15. console.log(Object.getOwnPropertyDescriptor(obj, 'name'));
  16. /**
  17. {
  18. value: 'zhufeng',
  19. writable: true,
  20. enumerable: true,
  21. configurable: true
  22. }
  23. */
  24. Object.seal(obj);
  25. console.log(Object.getOwnPropertyDescriptor(obj, 'name')); // seal 后 configurable 变为 false
  26. /**
  27. {
  28. value: 'zhufeng',
  29. writable: true,
  30. enumerable: true,
  31. configurable: false
  32. }
  33. */

冻结

  • Object.freeze() 可以使对象一个对象不能再添加新属性,也不可以删除旧属性,且不能修改属性的值。参数是目标对象,返回修改后的对象。
  • Object.isFrozen() 可以检测一个对象是否冻结,即是否可以增删改。参数是目标对象,返回布尔值,true 表示已经冻结不可再增删改,false 反之 ```javascript var obj = new Object(); Object.isExtensible(obj); // true Object.isSealed(obj); // false Object.isFrozen(obj); // false Object.freeze(obj); Object.isExtensible(obj); // false,注意 freeze 后对象的 isExtensible() 也随之改变 Object.isSealed(obj); // true,注意 freeze 后对象的 isSealed() 也随之改变 Object.isFrozen(obj); // true var obj = Object.freeze({ name: ‘zhufeng’ });

// 直接定义新的属性会报错 Object.defineProperty(obj, ‘name’, { value: ‘zhufeng’ });

obj.name = ‘zhufeng’; obj.name; // undefined

delete obj.name; // 删除失败,返回 false

obj.name = ‘jiagou’; obj.name; // 仍然是 “zhufeng”

  1. - [ ] 深冻结 (类似深拷贝)
  2. <a name="AuJ12"></a>
  3. ## 5. +号
  4. - 两个操作数如果是number则直接相加出结果
  5. - 如果其中有一个操作数为string,则将另一个操作数隐式的转换为string,然后进行字符串拼接得出结果
  6. - 如果操作数为对象或者是数组这种复杂的数据类型,那么就将两个操作数都转换为字符串,进行拼接
  7. - 如果操作数是像boolean这种的简单数据类型,那么就将操作数转换为number相加得出结果
  8. - [ ] + { } 因为[]会被强制转换为"", 然后+运算符 链接一个{ }, { }强制转换为字符串就是"[object Object]"
  9. - { } 当作一个空代码块,`+[]`是强制将[]转换为number,转换的过程是 +[] => +"" =>0 最终的结果就是0
  10. ```javascript
  11. []+{} // [object Object] []转为"",{}转为[object Object]
  12. {}+[] // +[]强制转为number +[] -> +'' -> 0 最终结果为0 {}为代码块
  13. {}+0 //0
  14. []+0 //"0 "
  15. [].toString() //0

6.柯里化

1.bind

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

  1. // 使用举例
  2. (function (prototype) {
  3. function bind(context = global, ...outerArgs) {
  4. return (...innerArgs) => {
  5. return this.call(context, ...outerArgs, ...innerArgs);
  6. }
  7. }
  8. prototype.bind = bind;
  9. })(Function.prototype);
  10. function sum(...args) {
  11. return this.prefix + args.reduce((acc, curr) => acc + curr, 0);
  12. }
  13. let obj = { prefix: '$' };
  14. let bindSum = sum.bind(obj, 1, 2, 3);
  15. console.log(bindSum(4, 5)); //$15
  1. // bind实现
  2. Function.prototype.bind = function (context, ...args) {
  3. const fn = Symbol('fn')
  4. context[fn] = this
  5. return function (...others) {
  6. const result = context[fn](...args, ...others)
  7. delete context[fn]
  8. return result
  9. }
  10. }
  1. function Point(x, y) {
  2. this.x = x;
  3. this.y = y;
  4. }
  5. Point.prototype.toString = function () {
  6. return this.x + ',' + this.y;
  7. }
  8. let YPoint = Point.bind(null, 1);
  9. let axiosPoint = new YPoint(2);
  10. console.log(axiosPoint.toString()) // '1,2'
  11. console.log(axiosPoint instanceof Point) // true
  12. console.log(axiosPoint instanceof YPoint) // tue

上面的bind实现是不支持new的

image.png

  1. Function.prototype.bind = function(context,..outerAgrs){
  2. let thatFunc = this; //缓存当前的函数
  3. let fBound = function(...innerAgrs){
  4. //如果在这里判断我这个函数是new来调用的还是直接调用
  5. return thatFunc.apply(
  6. // 如果是在new 这绑定的后函数的话,则bind绑定的时候传的context就没有用了
  7. this instanceof thatFunc ? this : context, [...outerAgrs,...innderArgs]
  8. );
  9. };
  10. fBound.prototype = Object.create(thatFunc.prototype); // 不能直接=,会污染原型对象
  11. return fBound;
  12. }

2.add

  1. add(1); // 1
  2. add(1)(2); // 3
  3. add(1)(2)(3); // 6
  4. add(1)(2,3); // 6
  5. add(1,2)(3); // 6
  6. add(1,2,3); // 6
  1. // 第一写法
  2. const add = (function (total) {
  3. let allArgs = [];
  4. function _add(...args) {
  5. allArgs = [...allArgs, ...args];
  6. if (allArgs.length >= total) {
  7. let ret = allArgs.reduce((pre, cur) => pre + cur, 0);
  8. allArgs.length = 0; // 要清空数组
  9. return ret;
  10. } else {
  11. return _add
  12. }
  13. }
  14. return _add
  15. })(5);
  1. // 第二种写法
  2. function add(..args){
  3. let _add = add.bind(null,...args);
  4. _add.toString = function(){
  5. return args.reduce((pre, cur) => pre + cur, 0);
  6. }
  7. return _add();
  8. }

函数柯里化就是把接受多个参数的函数变换成接受一个单一参数的函数,并且返回接受余下参数返回结果的技术。

  1. function curry(fn,...args){
  2. return args.length < fn.length ? (...innerArgs)=>{ // fn.length表示形参的数量
  3. return curry(fn,..args,...innerArgs);
  4. } : fn(...args)
  5. }

7.拷贝

1 JSON.parse

  • 无法支持所有类型,比如函数

    1. let obj = { name: 'zhufeng', age: 10 };
    2. console.log(JSON.parse(JSON.stringify(obj)));

    2 浅拷贝

    1. function clone(source) {
    2. let target = {};
    3. for (const key in source) {
    4. target[key] = source[key];
    5. }
    6. return target;
    7. };

    3 深拷贝

  • 支持对象和数组 ```javascript let obj = { name: ‘zhufeng’, age: 10, home: { name: ‘北京’ }, hobbies: [‘抽烟’, ‘喝酒’, ‘烫头’] }; function clone(source) { if (typeof source === ‘object’) {

    1. let target = Array.isArray(source) ? [] : {};
    2. for (const key in source) {
    3. target[key] = clone(source[key]);
    4. }
    5. return target;

    } return source;

}; let cloned = clone(obj); console.log(Array.isArray(cloned.hobbies));

  1. <a name="a6HO2"></a>
  2. ### 4 循环引用
  3. ```javascript
  4. let obj = {
  5. name: 'zhufeng',
  6. age: 10,
  7. home: { name: '北京' },
  8. hobbies: ['抽烟', '喝酒', '烫头']
  9. };
  10. obj.obj = obj;
  11. function clone(source, map = new Map()) {
  12. if (typeof source === 'object') {
  13. if (map.get(source)) {
  14. return map.get(source);
  15. }
  16. let target = Array.isArray(source) ? [] : {};
  17. map.set(source, target);
  18. for (const key in source) {
  19. target[key] = clone(source[key], map);
  20. }
  21. return target;
  22. }
  23. return source;
  24. };
  25. let cloned = clone(obj);
  26. console.log(cloned.obj);

6 精确类型

6.1 判断类型方式

  • typeof
    • 返回结果都是字符串
    • 字符串中包含了对应的数据类型 number string boolean undefined symbol
    • typeof null == ‘object’
    • typeof {} [] /&$/ Date== ‘object’
  • instanceof
  • Object.prototype.toString.call ```javascript let obj = { married: true, age: 10, name: ‘zhufeng’, girlfriend: null, boyfriend: undefined, flag: Symbol(‘man’), home: { name: ‘北京’ }, set: new Set(), map: new Map(), getName: function () { }, hobbies: [‘抽烟’, ‘喝酒’, ‘烫头’], error: new Error(‘error’), pattern: /^regexp$/ig, math: Math, json: JSON, document: document, window: window }; obj.set.add(1); obj.map.set(‘name’, ‘value’); obj.obj = obj;

let OBJECT_TYPES = [{}, [], new Map(), new Set(), new Error(), new Date(), /^$/].map(item => getType(item)); const MAP_TYPE = getType(new Map()); const SET_TYPE = getType(new Set()); const CONSTRUCT_TYPE = [new Error(), new Date()].map(item => getType(item)); const SYMBOL_TYPE = getType(Symbol(‘1’)); const REGEXP_TYPE = getType(/^$/); function clone(source, map = new Map()) { let type = getType(source); if (!OBJECT_TYPES.includes(type)) {//基本数据类型 return source; } if (map.get(source)) { return map.get(source); } if (CONSTRUCT_TYPE.includes(type)) { return new source.constructor(source); } let target = new source.constructor(); map.set(source, target);

  1. if (SYMBOL_TYPE === type) {
  2. return Object(Symbol.prototype.valueOf.call(source));
  3. }
  4. if (REGEXP_TYPE === type) {
  5. const flags = /\w*$/;
  6. const target = new source.constructor(source.source, flags.exec(source));
  7. target.lastIndex = source.lastIndex;
  8. return target;
  9. }
  10. if (SET_TYPE === type) {
  11. source.forEach(value => {
  12. target.add(clone(value, map));
  13. });
  14. return target;
  15. }
  16. if (MAP_TYPE === type) {
  17. source.forEach((value, key) => {
  18. target.set(key, clone(value, map));
  19. });
  20. return target;
  21. }
  22. let keys = Object.keys(source);
  23. let length = keys.length;
  24. let index = 0;
  25. while (index < length) {
  26. target[keys[index]] = clone(source[keys[index]], map);
  27. index++;
  28. }
  29. return target;

};

function getType(source) { return Object.prototype.toString.call(source); } let cloned = clone(obj); console.log(cloned); console.log(obj.home === cloned.home); console.log(obj.set === cloned.set); console.log(obj.map === cloned.map); / [object Boolean] [object Number] [object String] [object Null] [object Undefined] [object Symbol] [object Object] [object Function] [object Array] [object Error] [object RegExp] [object Math] [object JSON] [object HTMLDocument] [object Window]” / ```