类对象是一种用于创建和管理对象的架构或概念
class Person {
constructor(name,age){
this.name = name;
this.age = age;
}
sayHello(){
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person('John', 25);
person1.sayHello();
使用class关键字定义类对象,它使用constructor方法用于初始化实例对象的属性,还可以包含其他方法来定义对象的行为。
function Person(name,age)
{
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
var p1 = new Person("John", 25);
p1.sayHello();
利用函数作为构造函数来创建类对象。在构造函数内部,使用this关键字来定义实例对象的属性,通过在构造函数的原型上添加方法来定义对象的共享行为。
类数组对象指拥有“length”属性,且属性名是自然数(索引)的对象,但它并不是真正的数组,不能使用数组的内置方法。
特征:
常见的类数组对象:
Hello
效果:
Array.fill()方法用于将一个数组中的所有元素从起始索引到终止索引填充为指定的值()
语法:
arr.fill(value,start)
// 创建一个长度为5的数组,并用0填充
const arr1 = new Array(5).fill(0)
console.log(arr1)
// 从索引1到索引3填充为1
const arr2 = [1,2,3,4,5]
arr2.fill(1, 1, 3)
console.log(arr2)
Array.from()方法从一个类似数组或可迭代对象创建一个新的、浅拷贝的数组。
它可以将类数组对象或可迭代对象转换为真正的数组。
语法:
// 将字符串转为数组
const str = 'hello'
const arr1 = Array.from(str)
console.log(arr1) // ["h", "e", "l", "l", "o"]
// 将Set转为数组
const set = new Set([1,2,3,4,5])
const arr2 = Array.from(set)
console.log(arr2) // [1,2,3,4,5]
// 使用映射函数
const arr3 = Array.from([1,2,3], x => x * 2)
console.log(arr3) // [2,4,6]
// 将类数组对象转换为数组
function sum()
{
const args = Array.from(arguments);
return args.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1,2,3)) // 6
call、apply、bind作用是:“改变函数执行时的上下文,即改变函数运行时的this指向”。
下面例子中,需要改变this指向:
var name = 'John';
const obj = {
name:'Jane',
say:function(){
console.log(this.name);
}
}
obj.say(); // Jane
setTimeout(obj.say,0); // John
在setTimeout()中调用的obj.say()方法是被当做“普通函数”来执行,普通函数的this指向window,所以输出John
apply(thisArg,argsArray),改变this指向后原函数会立即执行,此方法只是临时改变this指向一次
function f(...args){
console.log(this,args)
}
let obj = {
name:'张三'
}
f.apply(obj,[1,2]); // obj, [1, 2]
f([1,2]) // window [1,2
call(thisArg,arg1,arg2,...,argN),此方法也只是临时改变this指向一次
function f(...args){
console.log(this,args)
}
let obj = {
name:'张三'
}
f.call(obj,1,2); // obj, [1, 2]
f(1,2) // window [1,2]
bind(thisArg,arg1,arg2,...,argN),改变this指向后不会立即执行,而是返回一个永久改变this指向的函数
function f(...args){
console.log(this,args)
}
let obj = {
name:'张三'
}
const bindF = f.bind(obj);
bindF(1,2) // {name: "张三"} [1,2]
f(1,2) // window [1,2]