在Javascript中,有没有办法强制开发人员使用new
关键字来创建新对象?
我知道每次执行以下操作时,Javascript都会创建一个新对象:
var module=function(){}
var module = new module();
在Javascript中,有没有办法强制开发人员使用new
关键字来创建新对象?
我知道每次执行以下操作时,Javascript都会创建一个新对象:
var module=function(){}
var module = new module();
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)
new
而不是为他们做,可以在 if
内部抛出异常。 - Quentinfunction 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
var new module = module();
不是有效的 JavaScript 代码。 - thefourtheye