手动实现一个call方法
Function.prototype.myCall = function (context, ...rest) {
context = context || window;
context.fn = this;
let ret = context.fn(...rest);
delete context.fn;
return ret;
}
let obj = {
name: 1
}
function getName(a, b, c) {
return this;
}
let ret = getName.myCall(obj, 2, 3, 4);
console.log(ret);
手写call方法
Function.prototype.myCall = function (context, ...rest) {
context = context || window;
context.fn = this;
let ret = context.fn(...rest);
delete context.fn;
return ret;
}
let obj = {
name: 1
}
function getName(a, b, c) {
return this;
}
let ret = getName.myCall(obj, 2, 3, 4);
console.log(ret);
手动实现深拷贝
const deepClone = (obj) => {
let deepObj = Array.isArray(obj) ? [] : {};
if (obj && typeof obj === "object") {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof key === "object") {
deepObj[key] = deepClone(obj[key]);
} else {
deepObj[key] = obj[key];
}
}
}
}
return deepObj;
};
const obj = {
name: 1,
age: 2,
like: {
sing: "changge",
dance: "tiaowu",
play: {
wanshouji: 1,
xiedaima: 2,
},
},
};
const newObj = deepClone(obj);
console.log(newObj);
手写promise函数
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECT = 'reject';
function myPromise(fn) {
let _this = this;
this.state = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfillList = [];
this.onRejectList = [];
function reslove(value) {
_this.state = FULFILLED;
_this.value = value;
_this.onFulfillList.forEach((item) => item(value));
}
function reject(reason) {
_this.state = REJECT;
_this.reason = reason;
_this.onRejectList.forEach((item) => item(reason));
}
try {
fn(reslove, reject);
} catch (error) {
reject(error);
}
myPromise.prototype.then = function(res, rej) {
if (this.state === 'fulfilled') {
typeof res === 'function' && res(this.value);
}
if (this.state === 'reject') {
typeof rej === 'function' && rej(this.reason);
}
if (this.state === 'pending') {
typeof res === 'function' && this.onFulfillList.push(res);
typeof rej === 'function' && this.onRejectList.push(rej);
}
};
字符串段横行命名替换成驼峰
function humpString(str) {
if (str) {
return str.replace(/_\w/g, (lineStr) => {
return lineStr.slice(1).toUpperCase();
});
}
}
function humpString(str) {
if (str) {
const strArr = str.split("_");
for (let i = 1; i < strArr.length; i++) {
strArr[i] = strArr[i].slice(0, 1).toUpperCase() + strArr[i].slice(1);
}
return strArr.join("");
}
}
new操作符的实现
function _new(constructor, ...args) {
if (typeof constructor !== "function") {
throw new Error("constructor must be a function");
}
let obj = new Object();
obj.__proto__ = Object.create(constructor.prototype);
let res = constructor.apply(obj, args);
let isObject = typeof res === "object" && res !== null;
let isFunction = typeof res === "function";
return isObject || isFunction ? res : obj;
}