携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情
函数柯理化
一种函数的封装形式
把一个函数的两个参数拆开成为两个函数, 每个函数一个参数
多个参数的时候
把第一个参数单独提取出来
// 封装: 使用正则去验证用户名
function fn(reg, name) {
return reg.test(name)
}
// 使用的时候
const reg = /[^_]\w{5,11}/
const res = fn(reg, 'guoxiang')
const res2 = fn(reg, 'guoxiang3')
console.log(res)
console.log(res2)
// 以闭包的形式进行封装
function testName(reg) {
return function (username) {
return reg.test(username)
} }
// res 接收的是 函数内部 返回的函数
const res = testName(/^[^_]\w{5,11}$/)
// 真正进行代码开发的时候
const res2 = res('jason')
console.log(res2)
循环绑定事件
需求: 给每一个 button 绑定一个点击事件
点击每一个 button 的时候返回对应这个按钮的索引
以前的解决思路:
1. 循环的时候存储索引数据在元素身上
2. 利用闭包
//html部分
<button>1</button>
<button>2</button>
<button>3</button>
//js部分
var btns= document.querySelectorAll('button')
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = (function (index) {
// 随着循环, 每一次这个自执行函数都会执行
// 这个被 return 出去的函数才是事件处理函数呢
return function () {
console.log('我执行了')
console.log(index)
}
})(i)
}
继承 extend
构造函数的应用
当多个构造函数需要使用一些共同的方法或者属性的时候
我们需要把这些共同的东西单写一个公共的构造函数
方便其他的构造函数去继承自这个公共的构造函数的属性
概念
让 乙 构造函数的实例能够使用 甲 构造函数的属性和方法
我们管 乙 构造函数叫做 甲 构造函数的子类
我们管 甲 构造函数叫做 乙 构造函数的父类
** 目的:**
让 乙 构造函数能够使用 甲 构造函数的属性和方法
如果一个 类 继承自 Perosn
可以使用 name, age, sayHi
// 动物类
function Animal(name, age) {
this.name = name this.age = age
}
Animal.prototype.say = function () {
console.log('各种声音') }
// 猫类
function Cat(eye) {
this.eye = eye
}
Cat.prototype.xingwei = function () {
console.log('抓老鼠') }
// 鸟类 function Bird(body) {
this.body = body }
Bird.prototype.fly = function () {
console.log('飞') }
const c = new Cat('蓝黄')
console.log(c)
const b = new Bird('翅膀')
console.log(b)
原型继承
利用改变 原型链 的方式来达到继承效果
直接把父类的实例当作子类的 prototype
构造函数的原型 对象
我把你的原型赋值为一个新的对象
new Perosn 的时候, 得到的也是一个新的对象
核心代码: 字类.prototype = new 父类
原型继承的优缺点
优点: 构造函数体内和原型上的都可以继承
缺点:
1. 一个构造函数的内容, 在两个位置传递参数
2. 继承来的属性不再子类实例的身上
// 子类
function Student(gender) {
this.gender = gender }
// 直接把父类的实例当作字类的原型对象
Student.prototype = new Person('Jason', 18)
const s = new Student('男')
console.log(s)
// 现在开始
// Student.prototype = {
// name: 'Jason',
// age: 18,
// __proto__: {
// Person.prototype
// constructor: Person,
// sayHi: function () { },
// __proto__: Object.prototype
// }
// }
//当你 new Student
s = {
gender: '男',
__proto__: {
// Student.prototype 也是 Person 的实例
name: 'Jack',
age: 18,
__proto__: {
// Person.prototype
constructor: Person,
sayHi: function () { },
__proto__: Object.prototype
}
}
}
//仔细观察一下这两个的区别,
今天是周六 ,炎热的天气伴随着雨水蒸发起来,明天就是立秋了,炎热的夏天马上就结束了,马上迎来就是秋高气爽的季节,让我们一起行动起来去迎接这个美好的日子,加油