大家首先来看一片代码:
这个代码很简单 定义了一个简单的 greeter 原型 、
接受name作为参数。然后再原型中加入了greet 方法
实例化之后传入参数调用 greet方法。打印出hello world
function DelayedGreeter(name){
this.name=name;
}
DelayedGreeter.prototype.greet=function(){
console.log('Hello '+this.name);
};
const greeter=new DelayedGreeter('World'); //打印出 Hello world
greeter.greet();
接着 咱们在greet中加入一个setimeout函数
function DelayedGreeter(name){
this.name=name;
}
DelayedGreeter.prototype.greet=function(){
setTimeout(function cb(){
console.log('Hello '+this.name);
},500);
};
const greeter=new DelayedGreeter('World'); //打印出 Hello undefined
greeter.greet();
这时候打印出hello undefined
这是为什么呢。
1. 这个超时回掉函数的作用域和 greet方法的作用域是不同的,this的值是undefined.
在 node.js 引入箭头函数之前 为了解决这个问题需要使用bind函数修改greet方法,如下
function DelayedGreeter(name){
this.name=name;
}
DelayedGreeter.prototype.greet=function(){
setTimeout( (function cb(){
console.log('Hello '+this.name);
}).bind(this),500);
};
const greeter=new DelayedGreeter('World'); //打印出 Hello World
greeter.greet();
但是有了箭头函数之后 由于它们是绑定到自身作用域的 因此可以只使用一个箭头函数作为回调来解决这个问题
function DelayedGreeter(name){
this.name=name;
}
DelayedGreeter.prototype.greet=function(){
setTimeout( ()=>console.log('Hello' + this.name),500);
};
const greeter=new DelayedGreeter('World'); //打印出 Hello world
greeter.greet();