返回ES6中类以外的值 [英] Return a value other than the class in ES6

查看:110
本文介绍了返回ES6中类以外的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在测试ES6的类,我注意到,当创建一个类,你不能指定的构造函数给定的值。

Recently I've been testing out classes with ES6, I've noticed that when creating a class you cannot specify the value given by the constructor.

ES5这是可能的。

在这两种情况下,我将实例化类与 new MyClass
原因我想这样做,所以我可以返回一个只有函数的当前类的子集。

In both cases I would instantiate the class with new MyClass The reason I want to do this is so I can return a subset of the current class with only functions on it.

var MyClass = function() {
  this.initVar = 'Blah'

  return 'My Class was init with: ' + this.initVar
}



ES6 - 返回 {}



ES6 - returns {}

class Bob {
  constructor() {
   return 'hello' 
  }
}


推荐答案

根据 文章从TC39网站,ES6类语法有一个隐式构造函数,如果类定义中没有提供这样的函数,则调用该函数。

According to the Class article from the TC39 web site, the ES6 class syntax has an implicit constructor function that is called if no such function is provided in the class definition.

这可以通过提供自己的构造函数并返回任何你想要的对象来覆盖,例如:

This can be overridden by providing your own constructor and returning whatever object you want, e.g.:

class Bob {
  constructor(name) {
    return {hi: name};  // returns an object other than *this*.
  }
}

在操作中:

var bob = new Bob('bob');
console.log(bob.hi); // 'bob'

要扩展类,可以这样做:

To extend the class, you can do:

class Bill extends Bob {
}

但是, extends 也有一个隐式构造函数,所以它会返回一个继承自 Bob.prototype 。由于 hi 是在构造函数中定义的,并且未继承,因此您将获得:

However extends also has an implicit constructor, so it will return a new instance of Bill that inherits from Bob.prototype. Since hi was defined in the constructor and not inherited, you get:

var bill = new Bill('bill');
console.log(bill.hi);  // undefined

要像 Bob 一样初始化Bill,请提供一个构造函数调用 super ,并且因为您没有返回默认的,您需要返回结果,例如

To initialise Bill the same as Bob, provide a constructor that calls super, and because you aren't returning the default this, you need to return the result of that, e.g.

class Bill extends Bob {
  constructor(name) {
    return super(name);
  }
}

现在:

var bill = new Bill('bill');
console.log(bill.hi); // bill

测试于: http://www.es6fiddle.net/i50npw4w/

这篇关于返回ES6中类以外的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆