admin管理员组文章数量:1404050
Is there any way in Javascript to force the developer to use the new
keyword to create a new object?
I know that javascript creates a new object everytime I do this:
var module=function(){}
var module = new module();
Is there any way in Javascript to force the developer to use the new
keyword to create a new object?
I know that javascript creates a new object everytime I do this:
var module=function(){}
var module = new module();
Share
Improve this question
edited Mar 5, 2015 at 15:15
tzortzik
asked Mar 5, 2015 at 13:34
tzortziktzortzik
5,16310 gold badges60 silver badges95 bronze badges
3
- which developer?! You? Sure you can, just type new – Jamie Hutber Commented Mar 5, 2015 at 13:38
-
var new module = module();
is not valid JavaScript code. – thefourtheye Commented Mar 5, 2015 at 13:48 - Sorry, I copied the wrong thing. – tzortzik Commented Mar 5, 2015 at 15:15
2 Answers
Reset to default 10You can check the current this
object is an instance of the current constructor function, like this
function Person(name) {
if (!(this instanceof Person)) {
return new Person(name);
}
this.name = name;
}
You can then check if the object created without new
is of type Person
or not, like this
console.log(Person("thefourtheye") instanceof Person);
# true
Or, if you want the developer to explicitly use new
, then you can throw an error, as Quentin suggested, like this
function Person(name) {
if (!(this instanceof Person)) {
throw new Error("Person should be created with `new`")
}
this.name = name;
}
Person("thefourtheye");
will give
/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)
In ECMAScript 6, you can check the usage of the new
keyword thanks to new.target
. Is supported by all browsers, except IE.
The
new.target
property lets you detect whether a function or constructor was called using the new operator. In constructors and functions instantiated with the new operator, new.target returns a reference to the constructor or function. In normal function calls, new.target is undefined.
Developer Mozilla documentation
Take a look at the following example :
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
本文标签: functionjavascript force developer to instantiate with the new keywordStack Overflow
版权声明:本文标题:function - javascript force developer to instantiate with the new keyword - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744199214a2594886.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论