- 实现深拷贝
function deepClone (obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
let copy = {}
if (copy instanceof Array) {
copy = [];
}
for (let i in obj) {
/** 如果i是对象的自身属性 */
if (obj.hasOwnProperty(i)) {
obj[i] = deepClone(obj[i]);
}
}
return obj;
}
- 通过window.requestAnimationFrame实现定时器的需求, 每16ms去验证一下是否执行
function setInterVal (callback, n) {
let timer
const now = Date.now
let startTime = now()
let endTime = startTime
const loop = () => {
timer = window.requestAnimationFrame(loop)
endTime = now()
if (endTime - startTime >= n) {
startTime = endTime = now()
callback(timer)
}
}
timer = window.requestAnimationFrame(loop)
return timer
}
let a = 0
setInterVal(timer => {
console.log(a)
a++
if (a === 10) cancelAnimationFrame(timer)
}, 1000);
- 查找两个DOM节点的最近公共父节点
function findCommonParent(node1, node2) {
/** node1节点是node2的父节点 */
if(node1.contains(node2)){
return node1
/** node2节点是node1的父节点 */
} else if(node2.contains(node1)){
return node2
} else {
/** 如果两个节点是毫无关联的 递归查找最近父节点 */
return findCommonParent(node1.parent, node2)
}
}
- 实现instanceof
function myInstanceof(left, right) {
let proto = Object.getPrototypeOf(left), // 获取对象的原型
prototype = right.prototype; // 获取构造函数的 prototype 对象
// 判断构造函数的 prototype 对象是否在对象的原型链上
while (true) {
if (!proto) return false;
if (proto === prototype) return true;
proto = Object.getPrototypeOf(proto);
}
}
- new 操作符具体干了什么呢?如何实现?
- 首先创建了一个新的空对象
- 设置原型,将对象的原型设置为函数的 prototype 对象。
- 让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)
- 判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。
function objectFactory() {
let newObject = null,
constructor = Array.prototype.shift.call(arguments),
result = null;
// 参数判断
if (typeof constructor !== "function") {
console.error("type error");
return;
}
// 新建一个空对象,对象的原型为构造函数的 prototype 对象
newObject = Object.create(constructor.prototype);
// 将 this 指向新建对象,并执行函数
result = constructor.apply(newObject, arguments);
// 判断返回对象
let flag =
result && (typeof result === "object" || typeof result === "function");
// 判断返回结果
return flag ? result : newObject;
}
本文由博客一文多发平台 OpenWrite 发布!