返回 ES6 中的类以外的值

Return a value other than the class in ES6

本文关键字:返回 ES6      更新时间:2023-09-26

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

以前在 ES5 中这是可能的。

在这两种情况下,我都会用new MyClass来实例化类我想这样做的原因是我可以返回当前类的子集,上面只有函数。

ES5 - 返回My class was init with: Blah

var MyClass = function() {
  this.initVar = 'Blah'
  return 'My Class was init with: ' + this.initVar
}

ES6 - 返回{}

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

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

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

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

在行动中:

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

要扩展类,您可以执行以下操作:

class Bill extends Bob {
}

但是,extends也有一个隐式构造函数,因此它将返回从Bob.prototype继承的Bill的新实例。由于 hi 是在构造函数中定义的,而不是继承的,因此您可以得到:

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

若要像 Bob 一样初始化 Bill,请提供一个调用 super 的构造函数。此调用还将 Billthis 对象更改为 super 返回的值,例如

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

现在:

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

还值得注意的是,类声明的主体始终是严格的模式代码

作为可运行的代码段:

class Bob {
  constructor(name) {
    return {hi: name};  // returns an object other than *this*.
  }
}
var bob = new Bob('bob');
console.log(bob.hi); // 'bob'
class Bill extends Bob {
  constructor(name) {
    super(name);
  }
}
var bill = new Bill('bill');
console.log(bill.hi); // bill

在这种情况下

ES6实际上不返回{}而是返回类(构造函数)对象。类构造函数可以返回对象,但不能返回基元值。因此,它返回的不是 [字符串] "hello"而是返回 [对象] Bob 。任何值都可以这样返回:

class Bob {
  constructor() {
   return ()=>'hello';
  }
}
const bob = new Bob()();

返回的 [Function],因为它是一个对象,可以返回并立即触发以返回一些原始值,例如。[字符串] "hello" .

比较这些小提琴:es5 和ES6

你说在 es5 中可能的事情在 es6 中仍然是可能的,有一件小事,如果你使用 new 关键字,那么就会为该类创建一个新对象,如果你不使用 new,那么函数就会被执行。

  1. 因此,当你说,在 es5 和 es6 中var x= Bob();,你执行构造函数,而不是创建一个新对象,因此它会返回一些东西。

  2. 当你说,var x= new Bob();,你会得到一个新对象,由构造函数初始化。

这适用于 es5 和 es6,因为 es6 类没有做任何新东西,只是为了语法而引入。

编辑:在扩展类的情况下:你不能只在 es6 中扩展一个类并期望调用超级构造函数,你需要在子类构造函数中显式调用它。请参阅代码:

class Bob {
  constructor() {
    return {hi: 'bob'}
  }
}
class Bill extends Bob {
  constructor() {
   return super();// here you should retun the called super constructer
  }
}
var x=  Bob();
console.log(Bob);
 x= new Bill();
console.log(x.hi);

这就是为什么,这行不通,但这行得通..