JavaScript强制开发者使用new关键字实例化对象

3

在Javascript中,有没有办法强制开发人员使用new关键字来创建新对象?

我知道每次执行以下操作时,Javascript都会创建一个新对象:

var module=function(){}
var module = new module();

哪位开发者?!是你吗?当然可以,只需键入“new”。 - Jamie Hutber
var new module = module(); 不是有效的 JavaScript 代码。 - thefourtheye
抱歉,我复制了错误的内容。 - tzortzik
2个回答

10
您可以通过以下方式检查当前this对象是否是当前构造函数的实例:
function Person(name) {
    if (!(this instanceof Person)) {
        return new Person(name);
    }
    this.name = name;
}

您可以检查没有使用new关键字创建的对象是否为Person类型,如下所示:

console.log(Person("thefourtheye") instanceof Person);
# true

或者,如果您希望开发人员显式使用new,则可以像Quentin建议的那样抛出错误,如下所示。
function Person(name) {
    if (!(this instanceof Person)) {
        throw new Error("Person should be created with `new`")
    }
    this.name = name;
}

Person("thefourtheye");

将会给予

/home/thefourtheye/Desktop/Test.js:3
        throw new Error("Person should be created with `new`")
              ^
Error: Person should be created with `new`
    at Person (/home/thefourtheye/Desktop/Test.js:3:15)

2
或者如果你想强制他们使用 new 而不是为他们做,可以在 if 内部抛出异常。 - Quentin

2
在ECMAScript 6中,您可以通过使用new.target检查new关键字的用法。它被所有浏览器支持,除了IE。
new.target属性允许您检测函数或构造函数是否使用new运算符调用。在使用new运算符实例化的构造函数和函数中,new.target返回对构造函数或函数的引用。在普通函数调用中,new.target为undefined。
请参阅以下示例: Mozilla开发人员文档

function myconstructor() {
    if (!new.target) throw new Error('Constructor must be called using "new" keyword');
    return this;
}

let a = new myconstructor(); // OK
let b = myconstructor(); // ERROR


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接