定义类1
function My(name,age){
this.name=name;
this.age=age;
this.method=function(a,b){
alert(a+b);
}
}
My.static=function(){
confirm("My静态方法");
}
调用
new My().method(5,6);
My.static();
定义类2
<script>
// 定义类
class Person {
constructor(name) {
this.name = name;
}
m1() {
console.log("m1方法");
console.log(this);
}
}
// 定义对象共享方法
Person.prototype.m2 = function () {
console.log("所有对象共享m2方法");
}
var p1 = new Person("hu");
var p2 = new Person("li");
p1.m1();
p1.m2();
// m1方法this对象指向改成p2
p1.m1.call(p2)
</script>
this指向修改
var arr = [22, 44, 88, 33];
// 指定this指向并调用方法,arr必须为数组
var max = Math.max.apply(null, arr);
console.log(max);
// 改变this指向arr,返回改变this指向的新方法,但不调用原来方法
function bi() {
console.log(this);
}
var max = bi.bind(arr);
max();
剩余参数
// 定义剩余参数...args,one=1
var arr = [12, 45, 66];
function name(one, ...args) {
args.forEach((i) => {
console.log(i);
}
)
}
name(1, 55, 5454, 878);
伪数组转真数组
// 定义arr转为12, 45, 66,...arr=12,45,66
var arr = [12, 45, 66];
console.log(...arr);
// divs伪数组转真数组
var divs = document.querySelectorAll("input");
console.log(divs);
arr.push(...divs);
console.log(arr);
// 伪数组所有元素*100后生成新的数组
var likeArr = {
"0": 1, "1": 2, "length": 2
}
var arr = Array.from(likeArr, i => i * 100);
console.log(arr);
数组相关
// 查找对象数组中第一个id为12的对象
var likeArr = [{
id: 13, name: "hello"
}, {
id: 12, name: "hello"
}]
var obj = likeArr.find(item => item.id == 12);
console.log(obj);
// 查找对象数组中第一个>67的元素的索引
var arr = [8, 68, 88]
var index = arr.findIndex(i => { return i > 67 });
console.log(index);
// arr是否包含68
var a = arr.includes(68);
console.log(a);
模板字符串定义
// 模板字符串${}可以引用变量
var likeArr = [{
id: 13, name: "hello"
}, {
id: 12, name: "hello"
}]
let s = `这是对象${likeArr[0].id}`;
console.log(s);
// 字符串重复100次返回新串
var s = s.repeat(100);
console.log(s);
set集合去重
// set集合去重
var arr = [1, 5, 5, 8, 99, 99];
var set = new Set(arr);
console.log(set);
console.log(set.size);
set.forEach(i => { console.log(i); }
)
Object属性定义
var obj = { "one": 12, "two": 13 };
Object.defineProperty(obj, "sum", {
// 该属性可重新定义
configurable: true,
// 该属性可枚举
// enumerable:true,
// 该属性value可以修改
// writable:true,
set: function (value) {
this.one = value - 2;
this.two = value - 3;
},
get: function () {
return this.one + this.two;
}
})
// sum修改会调用set方法
obj.sum = 12;
console.log(obj.one);
obj.one = 0;
// 获得sum值会调用get方法
console.log(obj.sum);
构建内存中的document
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
<script>
var ul = document.querySelector("ul");
var frag = document.createDocumentFragment();
let child;
// 一个node只能有一个爹
while (child = ul.firstChild) {
frag.appendChild(child);
}
Array.from(frag.childNodes).forEach(i => {
if (i.nodeType === 1) {
i.textContent = "hello"
}
})
ul.appendChild(frag)
</script>
</html>
网友评论