你如何填充Javascript ES6`news.target`?

Leo*_*ang 6 javascript ecmascript-6

一些ES6功能非常容易填充:

if(!Array.prototype.find){
  Array.prototype.find=...
}
Run Code Online (Sandbox Code Playgroud)

你会怎么填充new.target?它在不受支持的浏览器中使用时会触发语法错误.try/catch不起作用,因为它是语法错误.我不必使用new.target,我只是好奇.

Tha*_*you 6

正如Jaromanda评论的那样,您无法填充新的语法,但您现在可以轻松解决一些 new.target用例问题

看一下new.target文档,你会看到一些可以用es5轻松编写的例子

new.target

function Foo() {
  if (!new.target) throw "Foo() must be called with new";
  console.log("Foo instantiated with new");
}

Foo(); // throws "Foo() must be called with new"
new Foo(); // logs "Foo instantiated with new"
Run Code Online (Sandbox Code Playgroud)

function Foo() {
  if (!(this instanceof Foo)) throw "Foo() must be called with new";
  console.log("Foo instantiated with new");
}

Foo(); // throws "Foo() must be called with new"
new Foo(); // logs "Foo instantiated with new"
Run Code Online (Sandbox Code Playgroud)

new.target

class A {
  constructor() {
    console.log(new.target.name);
  }
}

class B extends A { constructor() { super(); } }

var a = new A(); // logs "A"
var b = new B(); // logs "B"
Run Code Online (Sandbox Code Playgroud)

class A {
  constructor() {
    // class forces constructor to be called with `new`, so
    // `this` will always be set
    console.log(this.constructor.name);
  }
}

class B extends A { constructor() { super(); } }

var a = new A(); // logs "A"
var b = new B(); // logs "B"
Run Code Online (Sandbox Code Playgroud)

希望这有所帮助

  • 您可以重写一个抽象类构造函数,如`if(this.constructor.name === MyAbstractClass.name){throw new Error("无法实例化抽象类.");}`当使用抽象类扩展ES6类时它很有用.我不得不这样做,因为Babel仍然没有填充`new.target`所以我的Webpack UglifyJS插件正在读取它作为语法错误,打破了我的生产版本. (2认同)