码迷,mamicode.com
首页 > 其他好文 > 详细

new.target (es6)

时间:2016-05-05 01:52:53      阅读:545      评论:0      收藏:0      [点我收藏+]

标签:

今天无意间看到个词法new.target !

这是啥玩意儿 在我印象中 new 后跟的都是构造器!这是什么鬼~

技术分享

let F = function F() {
    if(!new.target)
      throw new Error(‘....‘)
    // ···
  };

查了下发现 其作用就是获取当前new的那个目标构造器  

可以保证函数是被当作构造器来使用的 没有就是undefined

以前的话 你想确保函数是被new的 而不是通过直接调用的 也许就会这么干

let F = function F() {
    if(!(this instanceof A)) 
      throw new Error(‘....‘);
    // ···
  };

不过有点b格的人还是可以这么写

let f = F.apply(Object.create(F.prototype) ,[])

在es6中 class 已经帮你检查过了(是否是new的)

new.target就知道当前是哪个class 下面输出 F2

class F2 extends F{
  constructor() {
    //‘F2‘
    console.log(new.target.name);
  }
}

 挺冷门的 兼容还挺惨的 chrome 46 firefox 41

 知道就行了

 

new.target (es6)

标签:

原文地址:http://www.cnblogs.com/daidaidai/p/5460347.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!