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

时间:2015-10-27 05:00:49

标签: javascript ecmascript-6

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

if(!Array.prototype.find){
  Array.prototype.find=...
}

您如何填充new.target?它在不受支持的浏览器中使用时会触发语法错误。 try/catch无法正常工作,因为它是语法错误。我不必使用new.target,我只是好奇。

1 个答案:

答案 0 :(得分:5)

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

看一下new.target docs你会看到一些可以用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"

<强>没有

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"

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"

<强>没有

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"

希望这有点帮助