温馨提示:距离2024年结束还剩18天,剩余约为4.92%...
使用闭包主要是为了设计私有的方法和变量。闭包的优点是可以避免全局变量的污染,缺点是闭包会常驻内存,会增大内存使用量,使用不当很容易造成内存泄露。在 js 中,函数即闭包,只有函数才会产生作用域的概念。
闭包的最大用处有两个,一个是可以读取函数内部的变量,另一个就是让这些变量始终保持在内存中。
闭包的另一个用处,是封装对象的私有属性和私有方法。
由于闭包会使得函数中的变量都被保存在内存中,内存消耗很大,所以不能滥用闭包,否则会造成网页的性能问题,在 IE 中可能导致内存泄露。
解决方法是,在退出函数之前,将不使用的局部变量全部删除。
W3C 中定义事件的发生经历三个阶段:
function creatPerson(name, age) {
var obj = new Object();
obj.name = name;
obj.age = age;
obj.sayName = function () {
window.alert(this.name);
};
return obj;
}
function Person(name, age) {
this.name = name;
this.age = age;
this.sayName = function () {
window.alert(this.name);
};
}
function Person() { }
Person.prototype = {
constructor: Person,
name: "Ning",
age: "23",
sayName: function () {
window.alert(this.name);
}
};
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
constructor: Person,
sayName: function () {
window.alert(this.name);
}
};
function SuperType(name) {
this.name = name;
this.sayName = function () {
window.alert(this.name);
};
}
function SubType(name, age) {
SuperType.call(this, name); //在这里借用了父类的构造函数
this.age = age;
}
function SuperType(name) {
this.name = name;
this.sayName = function () {
window.alert(this.name);
};
}
function SubType(name, age) {
this.supertype = SuperType; //在这里使用了对象冒充
this.supertype(name);
this.age = age;
}
function SuperType(name) {
this.name = name;
}
SuperType.prototype = {
sayName: function () {
window.alert(this.name);
}
};
function SubType(name, age) {
SuperType.call(this, name); //在这里继承属性
this.age = age;
}
SubType.prototype = new SuperType(); //这里继承方法
/** 创建连接 **/
var xhr = null;
xhr = new XMLHttpRequest()
/** 2. 连接服务器 **/
xhr.open('get', url, true)
/** 3. 发送请求 **/
xhr.send(null);
/** 4. 接受请求 **/
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
success(xhr.responseText);
} else {
/** false **/
fail && fail(xhr.status);
}
}
}
/** 异步加载地图 **/
export default function MapLoader() {
return new Promise((resolve, reject) => {
if (window.AMap) {
resolve(window.AMap)
} else {
var script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = ''
script.onerror = reject
document.head.appendChild(script)
}
window.initAMap = () => {
resolve(window.AMap)
}
})
}
var obj =eval('('+ str +')');
var obj = str.parseJSON();
var obj = JSON.parse(str);
JSON 对象转换为 JSON 字符串:
var last=obj.toJSONString();
var last=JSON.stringify(obj);
var arr = []; js
arr instanceof Array; // true
var arr = []; js
arr.constructor == Array; //true
var a = new Array(123); js
var b = new Date();
console.log(Array.isArray(a)); //true
console.log(Array.isArray(b)); //false
function ready(fn) {
if (document.addEventListener) { //标准浏览器
document.addEventListener('DOMContentLoaded', function () {
//注销事件, 避免反复触发
document.removeEventListener('DOMContentLoaded', arguments.callee, fa)
fn(); //执行函数
}, false);
} else if (document.attachEvent) { //IE
document.attachEvent('onreadystatechange', function () {
if (document.readyState == 'complete') {
document.detachEvent('onreadystatechange', arguments.callee);
fn(); //函数执行
}
});
}
};
function unique(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) { //第一个等同于第二个,splice 方法删除第二个
arr.splice(j, 1);
j--;
}
}
}
return arr;
}
var arr = [1, 1, 'true', 'true', true, true, 15, false, undefined, undefined, null]
console.log(unique(arr))
function unique(arr) {
return Array.from(new Set(arr))
}
var arr = [1, 1, 'true', 'true', true, true, 15, undefined, undefined, null]
console.log(unique(arr))
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type error!')
return
}
var array = [];
for (var i = 0; i < arr.length; i++) {
if (array.indexOf(arr[i]) === -1) {
array.push(arr[i])
}
}
return array;
}
var arr = [1, 1, 'true', 'true', true, true, 15, undefined, undefined, null]
console.log(unique(arr))
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type error!')
return;
}
arr = arr.sort()
var arrry = [arr[0]];
for (var i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
arrry.push(arr[i]);
}
}
return arrry;
}
var arr = [1, 1, 'true', 'true', true, true, 15, undefined, undefined, null]
console.log(unique(arr))
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type error!')
return
}
var arrry = [];
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (!obj[arr[i]]) {
arrry.push(arr[i])
obj[arr[i]] = 1
} else {
obj[arr[i]]++
}
}
return arrry;
}
var arr = [1, 1, 'true', 'true', true, true, 15, undefined, undefined, null]
console.log(unique(arr))
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type error!')
return
}
var array = [];
for (var i = 0; i < arr.length; i++) {
if (!array.includes(arr[i])) {//includes 检测数组是否有某个值
array.push(arr[i]);
}
}
return array
}
var arr = [1, 1, 'true', 'true', true, true, 15, undefined, undefined, null]
console.log(unique(arr))
// *使用 underscore 的源码来解释防抖动
// *underscore 防抖函数,返回函数连续调用时,空闲时间必须大于或等于 wait,func 才会执行
// * @param { function} func 回调函数
// * @param { number } wait 表示时间窗口的间隔
// * @param { boolean } immediate 设置为 ture 时,是否立即调用函数
// * @return { function} 返回客户调用函数
_.debounce = function (func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function () {
// 现在和上一次时间戳比较
var last = _.now() - timestamp;
// 如果当前间隔时间少于设定时间且大于 0 就重新设置定时器
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
// 否则的话就是时间到了执行回调函数
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function () {
context = this;
args = arguments;
// 获得时间戳
timestamp = _.now();
// 如果定时器不存在且立即执行函数
var callNow = immediate && !timeout;
// 如果定时器不存在就创建一个
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
// 如果需要立即执行函数的话 通过 apply 执行
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
/*** underscore 节流函数,返回函数连续调用时,func 执行频率限定为 次 / wait
* @param {function} func 回调函数
* @param {number} wait 表示时间窗口的间隔
* @param {object} options 如果想忽略开始函数的的调用,传入{leading: false}。
* 如果想忽略结尾函数的调用,传入{trailing: false}
* 两者不能共存,否则函数不能执行
* @return {function} 返回客户调用函数*/
_.throttle = function (func, wait, options) {
var context, args, result; var timeout = null;
var previous = 0;
// 如果 options 没传则设为空对象 if (!options) options = {}; // 定时器回调函数
var later = function () {
// 如果设置了 leading,就将 previous 设为 0 // 用于下面函数的第一个 if 判断
previous = options.leading === false ? 0 : _.now();
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function () {
var now = _.now();
// 首次进入前者肯定为 true
// 如果需要第一次不执行函数
// 就将上次时间戳设为当前的
// 这样在接下来计算 remaining 的值时会大于 0
if (!previous && options.leading === false) previous = now;
// 计算剩余时间
var remaining = wait - (now - previous);
context = this;
args = arguments;
// 如果当前调用已经大于上次调用时间 + wait
// 如果设置了 trailing,只会进入这个条件
// 如果没有设置 leading,那么第一次会进入这个条件
// 还有一点,你可能会觉得开启了定时器那么应该不会进入这个 if 条件了
// 其实还是会进入的,因为定时器的延时
// 并不是准确的时间,很可能你设置了 2 秒
// 但是他需要 2.2 秒才触发,这时候就会进入这个条件
if (remaining <= 0 || remaining > wait) {
// 如果存在定时器就清理掉否则会调用二次回调
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
// 判断是否设置了定时器和 trailing
// 没有的话就开启一个定时器
// 并且不能不能同时设置 leading 和 trailing
timeout = setTimeout(later, remaining);
}
return result;
};
};
var instance = null;
class Storage {
static getInstance() {
if (!instance) {
instance = new Storage();
}
return instance;
}
setItem = (key, value) => localStorage.setItem(key, value),
getItem = key => localStorage.getItem(key)
}
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: dataType,
success: function () { },
error: function () { }
});
try {
js
let response = await fetch(url);
let data = response.json();
console.log(data);
} catch (e) {
console.log("Oops, error", e);
}
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
window.onload = function () {
var demo = document.getElementById("demo");
demo.addEvent("test", function () { console.log("handler1") });
demo.addEvent("test", function () { console.log("handler2") });
demo.onclick = function () {
this.triggerEvent("test");
}
}
Element.prototype.addEvent = function (en, fn) {
this.pools = this.pools || {};
if (en in this.pools) {
this.pools[en].push(fn);
} else {
this.pools[en] = [];
this.pools[en].push(fn);
}
}
Element.prototype.triggerEvent = function (en) {
if (en in this.pools) {
var fns = this.pools[en];
for (var i = 0, il = fns.length; i < il; i++) {
fns[i]();
}
} else { return; }
}
var arr = [3, 1, 4, 6, 5, 7, 2]; js
function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = 0; j < arr.length - i - 1; j++) {
if (arr[j + 1] < arr[j]) {
var temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
console.log(bubbleSort(arr));
var arr = [3, 1, 4, 6, 5, 7, 2]; js
function quickSort(arr) {
if (arr.length == 0) {
return []; // 返回空数组
}
var cIndex = Math.floor(arr.length / 2);
var c = arr.splice(cIndex, 1);
var l = [];
var r = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] < c) {
l.push(arr[i]);
} else {
r.push(arr[i]);
}
}
return quickSort(l).concat(c, quickSort(r));
}
console.log(quickSort(arr));
var arr = [1, 2, 3, 4, 2, 1, 23, 543, 3]
Array.prototype.uniq = function () {
return [...new Set(this)];
}
console.log(arr.uniq())
// 或者 console.log([...new Set(arr)])
function isArray(arg) {
if (typeof arg === 'object') {
return Object.prototype.toString.call(arg) === '[object Array]';
}
return false;
}