构造函数

概念

构造函数 :是一种特殊的函数,主要用来初始化对象

使用场景:常规的 {...} 语法允许创建一个对象。比如我们创建了佩奇的对象,继续创建乔治的对象还需要重新写一

遍,此时可以通过构造函数来快速创建多个类似的对象

注意

  1. 构造函数在技术上是常规函数。
  2. 它们的命名以大写字母开头。
  3. 它们只能由 "new" 操作符来执行。

创建

构造函数语法:大写字母开头的函数

function Person (uname, gender, age) {
  // 设置属性
  // this调用者
  this.uname = uname
  this.gender = gender
  this.age = age 
}

// 实例化对象
const obj1 = new Person('小明', 'man', 22)
console.log(obj1)

说明:

  1. 使用 new 关键字调用函数的行为被称为实例化
  2. 实例化构造函数时没有参数时可以省略 ()
  3. 构造函数内部无需写return,返回值即为新创建的对象
  4. 构造函数内部的 return 返回的值无效,所以不要写return
  5. new Object() new Date() 也是实例化构造函数

实例化执行过程

  1. 创建新对象
  2. 构造函数this指向新对象
  3. 执行构造函数代码,修改this,添加新的属性
  4. 返回新对象

实例成员&静态成员

实例成员

通过构造函数创建的对象称为实例对象,实例对象中的属性和方法称为实例成员。

  • 为构造函数传入参数,动态创建结构相同但值不同的对象
  • 构造函数创建的实例对象彼此独立互不影响。

静态成员

构造函数的属性和方法被称为静态成员

  • 一般公共特征的属性或方法设置为静态成员
  • 静态成员方法中的 this 指向构造函数本身
// 构造函数:调用者是:实例化对象
function Person (uname, gender, age) {
  // 设置属性
  // this是指调用者
  this.uname = uname
  this.gender = gender
  this.age = age 
  this.say = function () {
    console.log('say')
  }
}

// 实例化对象
// 实例化对象拥有的属性和方法叫做实例成员
// 只有实例化对象才能使用实例成员(实例属性,实例方法)

const obj = new Person('小明', 'man', 22)
console.log(obj)

// 构造函数的属性和方法称为静态成员
// 只有构造函数才能使用静态成员(静态属性,静态方法)
Person.eye = 2
Person.arms = 2
Person.eat = function () {
  console.log('eat方法')
}

// 一个对象访问成员,如果找不到,返回undefined

内置构造函数

了解

在 JavaScript 中最主要的数据类型有 6 种:

基本数据类型:

字符串、数值、布尔、undefined、null

引用类型:

对象

但是,我们会发现有些特殊情况:

const str = 'string'
console.log(str.length)

其实字符串、数值、布尔、等基本类型也都有专门的构造函数,这些我们称为包装类型。

JS中几乎所有的数据都可以基于构成函数创建。

引用类型

Object,Array,RegExp,Date 等

包装类型

String,Number,Boolean 等

const str = 'asdasfafad'
console.log(str)

// 对象.属性
// 对象.方法()
// str.length
// str.trim()

// String:构造函数
// 包装类型
const str1 = new String('asdasfafad')
console.log(str1)

const num = new Number(2222)
console.log(num)

const bool = new Boolean(true)
console.log(bool)

Object

Object 是内置的构造函数,用于创建普通对象。

三个常用静态方法(静态方法就是只有构造函数Object可以调用的方法)

  1. Object.keys(实例对象) 静态方法获取对象中所有属性(键)
  2. Object.values(实例对象) 静态方法获取对象中所有属性值
  3. Object. assign(新创建实例对象,要拷贝的实例对象) 静态方法常用于对象拷贝
let obj = {
  name : '小明',
  gender : 'man',
  age : 18,
  index : 3,
  score : 1,
  eat : function () {
    console.log('eat')
  }

}

let o = {}


// Object: values 获取对象所有值,返回数组
console.log(Object.values(obj))

// Object: keys 获取对象所有属性和方法,返回数组
console.log(Object.keys(obj))

// Object.assign(新对象,就对象)实现浅拷贝,属性:新对象中有则替换,没有则添加
Object.assign(o, obj)
console.log(o, obj)


let newObj = {
  name : '123',
  lanhuge : 'chinese',
  skin : 'yellow',
}

Object.assign(newObj, obj)
console.log(newObj, obj)

Array

Array 是内置的构造函数,用于创建数组

数组常见实例方法-核心方法

  1. reduce

    语法:数组.reduce(function(累计值, 当前元素, 索引号, 源数组 ){}, 起始值)

    参数:起始值可以省略,如果写就作为第一次累计的起始值

    作用:返回函数累计处理的结果,经常用于求和等

    返回值:函数累计处理的结果

    累计值参数:

    1. 如果有起始值,则以起始值为准开始累计,初始: 累计值 = 起始值
    2. 如果没有起始值, 则累计值以数组的第一个数组元素作为起始值开始累计,初始:累计值 = arr[0]
    3. 后面每次遍历就会用后面的数组元素 累计到 累计值 里面 (类似求和里面的 sum )
    const arr = [1, 3, 4, 6]
    const re = arr.reduce( (prev, item) => prev + item)
    console.log(re)
    
    // ①:给员工每人涨薪 30%
    // ②:然后计算需要额外支出的费用
    
    const array = [{
      name: '张三',
      salary: 10000
      },
      {
      name: '李四',
      salary: 10000
      }, 
      {
      name: '王五',
      salary: 10000
      },
    ]
    //不能省略初始值,因为如果没有起始值,初始:累计值 = array[0],是一个对象
    const total = array.reduce((prev, item) => prev + item.salary * .3, 0)
    
    console.log(total)
    
  2. forEach

    语法:arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

    作用:forEach() 方法对数组的每个元素执行一次给定的函数。无返回值

    const arr = [4, 6, 7, 8, 10]
    let sum = 0
    arr.forEach(item => sum += item )
    console.log(sum)//35
    
  3. filter

    语法:var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

    作用:filter()方法创建一个新数组, 其包含符合函数条件的所有元素

    console.log(arr.filter(item => item >7))//[8, 10]
    
  4. map

    语法:let new_array = arr.map(function callback(currentValue[, index[, array]]){//Return element for new_array}[, thisArg])

    作用:map() 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

    console.log(arr.map(item => item * item))//[16, 36, 49, 64, 100]
    

数组常见方法-其他方法

数组常见方法

数组常见方法

const arr = [4, 6, 7, 8, 10]

// [,]可选参数
// find:遍历数组查找满足条件的第一个元素并返回
// 遍历数组查找大于7的第一个元素
// 执行次数:找到一个满足条件的就停止
console.log(arr.find(item => item > 7))//8

// findIndex:遍历数组查找满足条件的第一个元素的索引值并返回
// 遍历数组查找大于7的第一个元素的下标
// 执行次数:找到一个满足条件的就停止
console.log(arr.findIndex(item => item > 7))//3

// every:遍历数组查看每个元素是否满足条件,如果都满足,返回true,否则,返回false
// 遍历数组查看是否每一个元素都大于7
// 执行次数:找到一个不满足条件的就停止(false)或遍历完整数组
console.log(arr.every(item => item > 7))//false
// 若收到一个空数组,此方法在任何情况下都会返回 true。
console.log([].every(item => item > 7))//true

// some:遍历数组查看每个元素是否满足条件,如果有一个满足,返回true,都不满足,返回false
// 执行次数:找到一个满足条件的就停止
console.log(arr.some(item => item > 7))//true




// concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
// 语法:let new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
const array1 = ['a', 'b', 'c']
const array2 = ['e', 'f', 'g']
console.log(arr.concat(array1,array2))//[4, 6, 7, 8, 10, "a", "b", "c", "e", "f", "g"]

// copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。改变原数组
// 语法:arr.copyWithin(target[, start[, end]])
// end省略,表示拷贝从起始索引到结尾的元素
// copy to index 0 the element at index 3
console.log(arr.copyWithin(0, 3, 4))//[8, 6, 7, 8, 10]
// copy to index 1 all elements from index 3 to the end
console.log(arr.copyWithin(1, 3))//[8, 8, 10, 8, 10]


// fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。改变原数组
// 语法:arr.fill(value[, start[, end]])
console.log(arr.fill('*',2,4))//[4, 6, "*", "*", 10]
console.log(arr.fill('*',2))//[4, 6, "*", "*", "*"]
console.log(arr.fill('*'))//["*", "*", "*", "*", "*"]


// filter() 方法创建一个新数组, 其包含满足函数条件的所有元素。
console.log(arr.filter(item => item >7))//[8, 10]

数组常见方法- 伪数组转换为真数组

静态方法 Array.from()

<ui>
  <li></li>
  <li></li>
  <li></li>
</ui>
const lis = document.querySelectorAll('li')
// 伪数组转真数组
const arr = Array.from(lis)
arr.pop()
console.log(lis,arr)


let o = {
  0 : 'a',
  1 : 'b',
  2 : 'c',
  3 : 'd',
  length : 4
}

// 在转换伪数组时,必须有length属性
const array = Array.from(o)
console.log(array)

String

构建函数

  1. 字面量构建函数
  2. new String()
const str1 = 'abc'
const str2 = new String('abc')
console.log(str1,str2)

常见实例方法

string常见实例方法

const str = 'abcdsdfacfdsf'

// console.log(str.length)

// str.split('分隔符'):分割字符串,返回数组,与join作用相反
console.log(str.split('c'))
console.log(str.split(''))

// str.substring(indexStart[, indexEnd]):字符串截取
// 第一个参数:从哪个索引位置开始截取
// 第二个参数:从哪个索引位置截止截取(不包含)
// 如果只有一个参数,代表从该位置截取到结尾
// 特别注意:起始位置可以截取,结束位置截取不到

console.log(str.substring(2,4))//cd
console.log(str.substring(2))//cdsdfacfdsf

// str.startsWith(searchString[, position]):检测是否以某字符串开头
// 第一个参数:检测字符串,判断是否以该字符串开头
// 第二个参数:从哪个索引位置开始检测,不写默认0
console.log(str.startsWith('ab'))//true
console.log(str.startsWith('ab',2))//false

// str.includes(searchString[, position]):判断一个字符串中是否包含另一个字符串
// 第一个参数:检测字符串,判断是否包含该字符串
// 第二个参数:从哪个索引位置开始检测,不写默认0
console.log(str.includes('ab'))//true
console.log(str.includes('ab',10))//false


// str.indexOf(searchValue [, fromIndex]):对象中第一次出现的指定值的索引
// 第一个参数:检测字符串
// 第二个参数:从哪个索引位置开始检测,不写默认0
// 字符串中没有检测字符串返回-1
console.log(str.indexOf('fa'))//6
console.log(str.indexOf('fa',10))//-1

Number

Number 是内置的构造函数,用于创建数值

const num1 = 1
const num2 = new Number(2)
console.log(num1,num2)

常用方法:

toFixed() 设置保留小数位的长度

const price1 = 26.39656
const price2 = 26
// toFixed(n):四舍五入保留n位小数
// 整数在后面补上n位小数0
console.log(price1.toFixed(2),price2.toFixed(2))//26.40 26.00
posted @ 2022-05-26 18:25  丫丫learning  阅读(50)  评论(0编辑  收藏  举报