功能代码集合

JS原型链

1
2
3
4
5
6
7
8
9
10
11
function Person() {}
Person.prototype.name = "abc";
Person.prototype.sayName = function () {
console.log(this.name);
};

let person = new Person();

person.__proto__ = Person.prototype;
String.__proto__ = Function.prototype;
String.constructor = Function;

原型继承

1
2
3
4
5
6
7
8
9
10
function Parent() {
this.name = "Parent";
this.sex = "male";
}

function Child() {
this.name = "Child";
}

Child.prototype = new Parent();

构造函数继承

1
2
3
4
5
6
7
function Parent(name) {
this.name = name;
}

function Child() {
Parent.call(this, "Child");
}

组合继承

1
2
3
4
5
6
7
8
9
10
function Person(name) {
this.name = name;
}

function Child(name) {
Person.call(this, name);
}

Child.prototype = new Persion();
Child.prototype.constructor = Child;

new关键字

1
2
3
4
5
6
function _new(constructor, ...arg) {
let obj = {};
obj.__proto__ = constructor.prototype;
let res = constructor.apply(obj, arg);
return Object.prototype.toString.call(res) === "[object Object]" ? res : obj;
}

获取本周所有日期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export const getWeekDate = () => {
let weekDateList = [];
let weeks = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];

let today = new Date();
let currentDay = today.getDay();
let monday = new Date(today);
monday.setDate(today.getDate() - ((currentDay + 6) % 7));
for (let i = 0; i < 7; i++) {
let currentDate = new Date(monday);
currentDate.setDate(monday.getDate() + i);
let formatDate = dateFormat('MM-DD', new Date(currentDate));
let weekDate = `${formatDate} ${weeks[i]}`;
weekDateList.push(weekDate);
}
return weekDateList;
};

获取两个数组对象的差值

1
2
3
4
5
export const getArrayDiff = (arr1, arr2, key = 'id') => {
let keysInArr2 = new Set(arr2.map(item => item[key]));
let result = arr1.filter(item => !keysInArr2.has(item[key]));
return result;
};