引入了let和const解决了var变量提升带来的问题,同时引入箭头函数解决this访问问题。
function Person(firstname, lastname) { this.firstname = firstname; this.lastname = lastname;}//输出undefinedPerson.prototype.getNameInCallback = function () { setTimeout(functino(){ console.log(this.firstname, this.lastname); }, 1000);}//输出heyanboPerson.prototype.getNameInCallback = function () { setTimeout(functino(){ console.log(this.firstname, this.lastname); }.bind(this), 1000);}//输出heyanboPerson.prototype.getNameInCallback = function () {let context = this; setTimeout(functino(){ console.log(context.firstname, context.lastname); }.bind(this), 1000);}//输出heyanboPerson.prototype.getNameInCallback = function () { setTimeout(() => { //箭头函数里面的this可以直接当成一个变量,直接从父级作用域链中等变量对象中获取 console.log(this.firstname, this.lastname); }, 1000);}var p = new Person('he', 'yanbo');p.getNameInCallback();
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)