参考:
闭包可以让你从内部函数访问外部函数作用域
箭头函数相当于匿名函数, 简化了函数的定义
测试
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
<div id="root">
</div>
<script>
let obj = {
birth: 1990,
getAge1: function () {
let b1 = this.birth;
console.log(`b1====${b1}`);
let fn = () => new Date().getFullYear() - this.birth;
return fn();
},
getAge2: function () {
let that = this;
let b2 = this.birth;
console.log(`b2====${b2}`);
let fn1 = function () {
return new Date().getFullYear() - that.birth
};
console.log(`fn1=========${fn1()}`);
function fn2() {
return new Date().getFullYear() - that.birth
}
console.log(`fn2=========${fn2()}`);
function fn3() {
let date = new Date().getFullYear();
function inner() {
return date - that.birth
}
return inner()
}
console.log(`fn3=========${fn3()}`);
function fn4() {
let date = new Date().getFullYear();
return function () {
return date - that.birth
}
}
console.log(`fn4=========${fn4()()}`);
return fn3();
}
};
console.log(obj.getAge1());
console.log(obj.getAge2());
new Vue({
el: "#root",
})
</script>
</body>
</html>