您如何polyfill javaScript es6 n new.target`?

问题描述 投票:0回答:3
一些ES6功能真的很容易多填充:

if(!Array.prototype.find){ Array.prototype.find=... }
你怎么会polyfill

new.target

?当它在不支持的浏览器中使用时,它会触发语法错误。 
try/catch
不起作用,因为这是语法错误。我不必使用
new.target
,我大多只是好奇。
    

javascript ecmascript-6
3个回答
7
投票
some

sy

查看
new.targetdocs

您会看到一些可以用es5

编写的示例

new.target

没有

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"


我的函数通过接受函数的值而起作用,并且像

Function::bind


0
投票
返回了未定义的函数,要么返回与

function Abc (a) { this.a = a; console.log("this =", this, "; .a =", this.a, "; new.target:", new.target); } const A = requireNew(Abc); const a = new A(1);

运算符一起使用的构造函数函数。使用ES3:

this
使用

new.target

也是一种巧妙的处理方式,因为界限具有界限
new
arg,因此当界限函数的

0
投票
值不是预期的时,您知道它是用

来调用的。 Function.prototype.bind

操作员。 
this
然后包含
this
值:

new
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.