this
this是什么?
是函数中自带的一个变量, 指向函数运行时所在的对象 -- 非常灵活
它拥有不同的值,具体取决于它的使用位置:
使用场景?
为函数提供了另一种执行方式:
传统方案: 通过传递参数的方式 把对象传入
当前方案: 把函数作为参数传递到对象里执行 -- 反过来
// this关键词: 代表函数运行时所在的对象
// 从格式上分辨: 对象.方法名() 方法中的this 就是 前面的对象
// 矩形对象:
var r1 = { length: 10, width: 20 }
var r2 = { length: 100, width: 120 }
// area函数: 用于计算 矩形的面积 长 * 宽
// 传统做法:
function area(rect) {
return rect.length * rect.width
}
console.log(
area(r1), area(r2)
);
// this模式的函数
function area1() {
// this: 运行时服务的对象, 所在的
return this.length * this.width
}
// 1. 把 area1 存储到对象中 : 上门服务
r1.area1 = area1
console.log(r1)
// 2. 执行 r1 中的 area1 函数
console.log(
r1.area1() //调用函数
)
// 3. 执行完毕后, 从对象中删除.
delete r1.area1
call
什么是函数call
call: 短暂拜访
通俗来讲就是:你有点无聊,去找朋友借游戏机玩,玩完要归还,相当于清除
用完还回去没有了,要玩就再次借.
// 练习: 立方体
var c1 = { length: 10, width: 20, height: 30 }
// 1. 制作 volume 函数, 计算 体积=长*宽*高
// 把此函数放到 c1 中执行, 获取其体积
function volume() {
return this.length * this.width * this.height
}
console.log(volume.call(c1))
// 2. 制作 area 函数, 计算 面积=(长x宽 + 长x高 + 宽x高)*2
// 把此函数放到 c1 中执行, 获取其面积
function area() {
return (this.width * this.length + this.length * this.height + this.width * this.height) * 2
}
console.log(area.call(c1))
// 两题都通过使用c1来完成体积和面积的求取