学习笔记整理
这部分的学习笔记,整理于segmentfault和掘金社区的优质文章
复杂判断写法的改进
origin
const buttonClick = (status) => {
if (status == 1) {
sendLog('processing')
jumpTo('IndexPage')
} else if (status == 2) {
sendLog('fail')
jumpTo('FailPage')
} else if (status == 3) {
sendLog('success')
jumpTo('SuccessPage')
}
}
v1
switch(status) {
case1:
sendLog('processing')
jumpTo('IndexPage')
break;
case2:
sendLog('fail')
jumpTo('FailPage')
break;
case3:
sendLog('success')
jumpTo('SuccessPage')
break;
}
v2
const actions = {
'1': ['processing','IndexPage'],
'2': ['fail','FailPage'],
'3': ['success','SuccessPage']
}
const buttonClick = (status) => {
let action = action[status],
logName = action[0],
pageName = action[1]
sendLog(logName)
jumpTo(pageName)
}
v3
const actions = new Map([
[1, ['processing','IndexPage']],
[2, ['fail','FailPage']],
[3, ['success','SuccessPage']]
])
const onButtonClick = (status) => {
let action = actions.get(status)
sendLog(action[0])
jumpTo(action[1])
}
二元判断
不但需要判断status,而且还需要判断用户的身份
const actions = {
'guest_1':()=>{...},
'guest_2':()=>{...},
//....
}
const onButtonClick = (identity,status) => {
let action = actions[`${identity}_${status}`]
action.call(this)
}
this的指向问题
普通函数
this的指向无法在函数定义时确定,只有在函数执行时确定this到底指向谁
栗子1:
function a() {
var name = "fan";
console.log(this.name); //undefined
console.log(this); //window
}
a();
1中的this指向window,这里this指向调用它的对象,函数a实际上是被window对象调用
栗子2:
var o = {
name: "fan",
fn: function() {
console.log(this.name) //fan
}
}
o.fn();
2中this指向fan,同1中一样,this指向调用它的对象,函数fn被o对象调用
栗子3:
var o = {
name = "fan",
fn: function() {
console.log(this.name) //fan
}
}
window.o.fn();
按照之前的结论,this指向调用它的对象,这里应该指向window => 事实却指向了o
- 如果一个函数有this,但没有被上一级的对象调用,this指向window(非严格模式)
- 如果一个函数有this,被上一级对象调用,this指向上一级对象
栗子4(特殊情况)
var o = {
a: 10,
b: {
a:12,
fn: function() {
console.log(this.a) //undefined
}
}
}
var c = o.b.fn; //这里的fn没有被执行
c();
this指向的是最后调用它的对象,也就是看它执行的时候是谁调用的,4中将fn赋值给变量c时并没有执行
栗子5(显式绑定)
function foo () {
console.log(this.a)
}
var obj = { a: 1 }
var a = 2
foo() //2
foo.call(obj) //1
foo.apply(obj) //1
foo.bind(obj) //不会执行
箭头函数
箭头函数无法绑定this关键字,所以会自动向上层作用域寻找this,并使用上一层的this
//普通函数
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}, 1000); //undefined
}
};
//箭头函数
var obj = {
id: 42,
counter: function counter() {
setTimeout(() => {
console.log(this.id);
}, 1000); //42
}
};
综合练习
var name = 'window'
var person1 = {
name: 'person1',
foo1: function () {
console.log(this.name)
},
foo2: () => console.log(this.name),
foo3: function () {
return function () {
console.log(this.name)
}
},
foo4: function () {
return () => {
console.log(this.name)
}
}
}
var person2 = { name: 'person2' }
person1.foo1() // person1
person1.foo1.call(person2) // person2
person1.foo2() // window
person1.foo2.call(person2) // window
person1.foo3()() // window
person1.foo3.call(person2)()
person1.foo3().call(person2)
person1.foo4()() // preson1
person1.foo4.call(person2)()
person1.foo4().call(person2)