Handwritten instanceOf
Note:
- At the end of the loop, left==null;
function myInstanceOf(left, right) { let prototype = right.prototype; left = left.__proto__; while (true) { if (left === null) return false; if (left === prototype) return true; left = left.__proto__; }}Copy the code
Write a call
Note:
- The core is to execute this function as an attribute of a context parameter;
- To ensure that the new property defined does not appear on the context, use Symbol
- The return value is the result of execution
Function.prototype.myCall = function (context) { let fn = Symbol(); context = context || window; context[fn] = this; const args = [...arguments].slice(1); const result = context[fn](... args); delete context[fn]; return result; };Copy the code
Write a bind
Note:
- Save this, this currently refers to a function, because a new function is returned, in which this refers to the new object
- Record subsequent arguments passed to bind such as arg1 below;
- Record the arguments passed to the executing function, such as arg2 below:
- fn = u.bind(context,arg1); fn(arg2);
- Merge the two parameters and call Apply
Function.prototype.myCall = function (context) { let fn = Symbol(); context = context || window; context[fn] = this; const args = [...arguments].slice(1); const result = context[fn](... args); delete context[fn]; return result; };Copy the code
Write a new
function myNew(con) {
let obj = {};
obj.__proto__ = con.prototype;
con.call(obj);
return obj;
}
Copy the code
Handwritten image stabilization
function debounce(fn, time) {
let timer = null;
return function () {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn();
timer = null;
}, time);
};
}
Copy the code
Handwritten throttling
function throttle(fn, time) { let startTime = new Date(); return function () { let lastTime = new Date(); if (lastTime - startTime > time) { fn(); startTime = lastTime; }}; }Copy the code