In the function of js, how to tell whether it is a new or a function call? Instanceof can't be used, this can't distinguish

"use strict";

var C = {};

var arrKey = [], key;
var cntKey = Math.floor(Math.random() * 3) + 2;
for(var i=0; i<cntKey; iPP)
{
    key = Math.random();
    arrKey.push(key);

    C[key] = function(){
        console.log(this);
        // instanceof this  object
        //  new  
        console.log("new or call ?");
    };
}

console.log("----- ----- ----- ----- -----");
console.log(C);

console.log("----- ----- ----- ----- -----");
console.log("new C[?]");
new C[arrKey[Math.floor(Math.random() * cntKey)]]();

console.log("----- ----- ----- ----- -----");
console.log("call C[?]");
C[arrKey[Math.floor(Math.random() * cntKey)]]();

Aug.10,2021

The

ES6 function has a new.target meta attribute, so you can determine whether the new call or the function call . When
new calls , point to the constructor itself . When the
function calls , point to undefined .

function fn() {
    if(new.target) {
        console.log('new ')
    } else {
        console.log(' ')
    }
}
fn()  //  
new fn()  // new 

judge what it does. It doesn't matter how the function itself is called. No matter how deep it is, you don't know


'use strict';

var C = {};
function fn(){
    // console.log(this);
    // instanceof this  object
    //  new  
    // console.log('new or call ?');
    if(this.constructor === fn) { //fnarguments.callee;
        console.log("new ");
    } else {
        console.log("");
    }
};
var arrKey = [], key;
var cntKey = Math.floor(Math.random() * 3) + 2;
for(var i=0; i<cntKey; iPP)
{
    key = Math.random();
    arrKey.push(key);

    C[key] = fn;
}

console.log('new C[?]');
new C[arrKey[Math.floor(Math.random() * cntKey)]]();

console.log('----- ----- ----- ----- -----');
console.log('call C[?]');
C[arrKey[Math.floor(Math.random() * cntKey)]]();

:
new C[?]
new 
----- ----- ----- ----- -----
call C[?]
.
Menu