JavaScript - 函数A作为参数时,函数A中this的指向问题
- 本问题将引出ES6众多新特性中箭头函数的优点(
情况C ) - 在线测试:https://www.w3school.com.cn/tiy/t.asp?f=js_function_apply
一:情况A(this指向winodw对象 )

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript函数A作为参数时,函数A中this的指向问题</h1>
<script>
function Person() {
console.log(this);
this.age = 0;
setInterval(function growUp() {
console.log(this);
this.age++;
}, 1000);
}
var person = new Person();
</script>
</body>
</html>
二:情况B(this指向当前对象 )

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript函数A作为参数时,函数A中this的指向问题</h1>
<script>
function Person() {
console.log(this);
let self = this;
self.age = 0;
setInterval(function growUp() {
console.log(self);
self.age++;
}, 1000);
}
var person = new Person();
</script>
</body>
</html>
三:情况C(this指向当前对象,使用ES6箭头函数简写 )

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript函数A作为参数时,函数A中this的指向问题</h1>
<script>
function Person() {
console.log(this);
this.age = 0;
setInterval(()=>{
console.log(this);
this.age++;
}, 1000);
}
var person = new Person();
</script>
</body>
</html>
|