说说ES6 Class里面的this对象

来源:互联网 发布:打电话软件下载 编辑:程序博客网 时间:2024/06/06 00:24

废话不说,直接上代码,浅显易懂


class Animal {    constructor(){        this.type = 'animal'    }    says(say){        setTimeout(function(){            console.log(this.type + ' says ' + say)        }, 1000)    }//第一种是将this传给self,再用self来指代thissays1(say){var self = this;setTimeout(function(){console.log(self.type + " says1 " + say);},1000)}//第二种方法是用bind(this),即says2(say){setTimeout(function(){console.log(this.type + " says2 " + say);}.bind(this),1000);}//第三种方法是箭头函数says3(say){        setTimeout( () => {            console.log(this.type + ' says ' + say)        }, 1000)    }} var animal = new Animal() animal.says('hi')  //undefined says hi animal.says1('hi')  //animal says hi animal.says2('hi')  //animal says hi animal.says3('hi')  //animal says hi





原创粉丝点击