为了账号安全,请及时绑定邮箱和手机立即绑定

ES6箭头功能在原型上不起作用?

ES6箭头功能在原型上不起作用?

森林海 2019-11-18 18:25:41
当ES6 Arrow函数似乎无法使用prototype.object将函数分配给对象时。考虑以下示例:function Animal(name, type){ this.name = name;  this.type = type;  this.toString = () => `${this.name} is a ${this.type}`;}var myDog = new Animal('Max', 'Dog');console.log(myDog.toString()); //Max is a Dog在对象定义中显式使用arrow函数是可行的,但将Object函数与Object.prototype语法一起使用不能:function Animal2(name, type){  this.name = name;  this.type = type;}Animal2.prototype.toString = () => `${this.name} is a ${this.type}`;var myPet2 = new Animal2('Noah', 'cat');console.log(myPet2.toString()); //is a undefined就像概念证明一样,将Template字符串语法与Object.prototype语法结合使用确实可以:function Animal3(name, type){  this.name = name;  this.type = type;}Animal3.prototype.toString = function(){ return `${this.name} is a ${this.type}`;}var myPet3 = new Animal3('Joey', 'Kangaroo');console.log(myPet3.toString()); //Joey is a Kangaroo我是否缺少明显的东西?我觉得示例2应该在逻辑上起作用,但是我对输出感到困惑。我猜这是一个范围界定的问题,但是输出“是未定义的”让我望而却步。
查看完整描述

3 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

箭头函数提供了一个词法this。它使用在this评估功能时可用的。


从逻辑上讲,它等效于(以下无效代码,因为您不能使用名为的变量this):


(function(this){

   // code that uses "this"

 })(this)

在您的第一个示例中,arrow函数在构造函数中,并this指向新生成的实例。


在您的第三个示例中,未使用箭头功能,并且标准this行为照常运行(此功能在功能范围内)。


在第二个示例中,您使用了箭头函数,但是在评估范围内,它this是全局/未定义的。


查看完整回答
反对 回复 2019-11-18
?
弑天下

TA贡献1818条经验 获得超7个赞

您可以thisthis您打算使用的任何地方使用它。例如,假设你的对象有一个setup()功能,增加了多种功能本身,你会这样称呼它:myObj.setup()。该功能可以使用箭头功能添加所需的功能。另一个更典型的用例是使用需要访问this初始上下文的回调函数。

查看完整回答
反对 回复 2019-11-18
  • 3 回答
  • 0 关注
  • 342 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信