前端面试题集锦三

10 篇文章 0 订阅
5 篇文章 0 订阅

36.实现new方法

答:步骤:创建空对象,链接到原型,绑定this,返回新对象

function CreateNew () {

   let obj = {};
  let constructor = [].shift.call(arguments);
  obj._proto_ = constructor.prototype;
  let result = constructor.apply(obj, arguments);
  return typeof result === ‘object’ ? result : obj

}

37.实现一个call, bind,apply函数

答:将要改变的this指向的方法挂载到目标this上执行

// call

Function.prototype.call = function(context) {
if (typeof this !== ‘function’) { throw new TypeError(‘this is not function’)}
context = context || window
context.fn = this
let arg = […arguments].slice(1)
let result = context.fn(…arg)
delete context.fn
return result
}

// apply

Function.prototype.apply = function (context) {

  if (typeof this !== 'function') {

    throw new TypeError('this is not function')

  }

  context = context || window

  context.fn = this

  let result

  if (arguments[1]) {

    result = context.fn(...arguments[1])

  } else {

    result = context.fn()

  }

  delete context.fn

  return result

}

// bind

Function.prototype.bind = function (context) {

  if (typeof this !== 'function') {

    throw new TypeError('Error')

  }

  let _this = this

  let arg = [...arguments].slice(1)

  return function F() {

    // 处理函数使用new的情况

    if (this instanceof F) {

      return new _this(...arg, ...arguments)

    } else {

      return _this.apply(context, arg.concat(...arguments))

    }

  }

}

 

38.手写代码之浅拷贝、深拷贝的实现

答:浅拷贝:

(1): 扩展运算符 … let newObj = {…obj} 

(2): Object.assign 

(3): function shallowClone (obj) {

   var newObj = {};

   for ( var i in obj) {

      newObj[i] = obj[i];

   }

     return newObj;

}

 

深拷贝:

(1): JOSN.stringify()/JSON.parse() 标准JSON // 缺点:拷贝对象包含 正则表达式,函数,或者undefined等值会失败
(2): 递归拷贝 function deepClone(obj) {

  let copy = obj instanceof Array ? [] : {}

  for (let i in obj) {

    if (obj.hasOwnProperty(i)) {

      copy[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]

    }

  }

  return copy

}  

(3):  $.extend 

(4): lodash库

 

39.Object.create的基本实现原理

答:// 将传入的对象作为原型

Function create(obj) {
function F() {}
F.prototype = obj
return new F()
}

 

40.实现rem方案

答:// 提前执行,初始化 resize 事件不会执行

setRem()

// 原始配置

function setRem () {

  let doc = document.documentElement

  let width = doc.getBoundingClientRect().width

  let rem = width / 75

  doc.style.fontSize = rem + 'px'

}

// 监听窗口变化

addEventListener("resize", setRem)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值