node.js design patterns (the arrow function)

大家首先来看一片代码:
这个代码很简单 定义了一个简单的 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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值