Skip to main content

其他js相关

更准确的 setInterval

setTimeout +系统时间补偿

// 10秒倒计时
let countdown = 10;
function timer() {
let speed = 1000,
counter = 1,
start = Date.now();
function timer_() {
if (countdown === 0) {
return;
}
const real = counter * speed,
ideal = Date.now() - start;
counter++;
const diff = ideal - real;
countdown--;
setTimeout(() => {
timer_();
}, speed - diff);
}
setTimeout(() => {
timer_();
}, speed);
}

safeGet

const safeGet = (o, path) => {
try {
return path.split(".").reduce((o, k) => o[k], o);
} catch (error) {
return undefined;
}
};

模拟实现 Object.freeze

function myFreeze(obj) {
if (obj instanceof Object) {
Object.seal(obj);
let p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
Object.defineProperty(obj, p, { writable: false });
myFreeze(obj[p]);
}
}
}
}

深冻结。freeze 是浅冻结

function myFreeze(obj) {
Object.freeze(obj);
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const item = obj[key];
if (typeof item === "object" && item !== null) {
myFreeze(item);
}
}
}
return obj;
}
const person = {
name: "Lance",
grade: {
Math: 100,
IT: 90,
Chinese: 100,
},
a: {
b: {
c: 1,
},
},
};

myFreeze(person);

person.a.b.c = 2333;
console.log(person);

模拟实现 let 和 const

let

function outputNum(count) {
(function () {
for (var i = 0; i < count; i++) {
console.log(i);
}
})();
console.log(i);
}
outputNum(5);

const

function _const(key, value) {
window[key] = value;
Object.defineProperty(window, key, {
enumerable: false,
configurable: false,
get: function () {
return value;
},
set: function (newValue) {
if (newValue !== value) {
throw TypeError("这是只读变量,不可修改");
} else {
return value;
}
},
});
}