最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

function - javascript force developer to instantiate with the new keyword - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 10

You 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

发布评论

评论列表(0)

  1. 暂无评论