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)