new.target检测构造函数或构造方法受否用new 实例调用
new .target属性用于检测函数或构造方法是否用new调用 是则指向构造方法或函数引用 ,否则是undefined
函数调用:
1 function L(){ 2 var passed = false; 3 new function f() { 4 passed = (new.target === f); 5 }(); 6 (function() { 7 passed &= (new.target === undefined); 8 }()); 9 return passed; 10 } 11 L(); //return 1 12
1 function C() { 2 return x => new.target; 3 } 4 return new C()() === C && C()() === undefined; //true
构造方法调用:
1 class A{ 2 constructor(){ 3 console.log(new.target.name); 4 } 5 } 6 var a =new A(); //A 7 class B { 8 constructor(){ 9 console.log(new.target); 10 } 11 } 12 var b=new B(); // class B {constructor(){console.log(new.target);}}
游走大神世界,体验代码魅力