javascript - 检测构造函数中是否使用了 new 关键字?

标签 javascript object

在 JS 的构造函数对象中,如果它是在没有 new 关键字的情况下创建的,则“this”变量是对窗口而不是对象的引用。尝试检测它是否是一个特别明智的想法?

function MyObject ()
{
    if (this === window) {
        alert('[ERROR] Oopsy! You seem to have forgotten to use the "new" keyword.');
        return;
    }

    // Continue with the constructor...
}

// Call the constructor without the new keyword
obj = MyObject()

最佳答案

当关键字被省略时强制一个对象是相当常见的-

function Group(O){
    if(!(this instanceof Group)) return new Group(O);
    if(!O || typeof O!= 'object') O= {};
    for(var p in O){
        if(O.hasOwnProperty(p)) this[p]= O[p];
    }
}

关于javascript - 检测构造函数中是否使用了 new 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20250853/

相关文章:

java - 域对象行为如何

javascript - 为什么在Windows 10中(重新加载后)在Windows 10中崩溃的相同Electron应用程序在Windows 10中会崩溃?

javascript - 将值传递给 onclick

javascript - 页面在 Chrome、Firefox 和 IE 中运行良好,但在 iPad Safari 上会导致闪烁或崩溃

javascript - 未捕获的类型错误 : object is not a function onclick

node.js - JavaScript函数;在本地工作但不适用于 Lambda Minibootcamp

java - 尝试创建相同对象类型的两个实例,但最终得到两个引用同一对象的变量

javascript - Sails.js 通过 id 查找多个数据库条目

javascript - 为什么任务没有从本地存储中删除?

oop - Lua 元表和元方法 - 如何调用不同的成员函数