new.target是es6特性?? 这两处分别代表啥

请教
let PersonType2 = (function() {

"use strict";
const PersonType2 = function(name) {
    // 确认函数被调用时使用了 new
    if (typeof new.target === "undefined") {
        // 这两处new.target分别代表啥
        throw new Error("Constructor must be called with new.");
    }
    this.name = name;
}
Object.defineProperty(PersonType2.prototype, "sayName", {
    value: function() {
        // 确认函数被调用时没有使用 new
        if (typeof new.target !== "undefined") {
            // 这两处new.target分别代表啥
            throw new Error("Method cannot be called with new.");
        }
        console.log(this.name);
    },
    enumerable: false,
    writable: true,
    configurable: true
});
return PersonType2;

}());

阅读 3.8k
1 个回答

new.target属性允许你检测函数或构造方法是否是通过new运算符被调用的。在通过new运算符被初始化的函数或构造方法中,new.target返回一个指向构造方法或函数的引用。在普通的函数调用中,new.target 的值是undefined。

new.target语法由一个关键字"new",一个点,和一个属性名"target"组成。通常"new."的作用是提供属性访问的上下文,但这里"new."其实不是一个真正的对象。不过在构造方法调用中,new.target指向被new调用的构造函数,所以"new."成为了一个虚拟上下文。

new.target属性是一个可以被所有函数访问的元属性。在箭头函数中,new.target指向外围函数的new.target。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题