I was reading about the ECMAScript 2015 new.target property. I thought it was interesting, I could configure a function using the new operator, and then call it by a normal call. But for some reason, this doesn't seem to work. This is my test code.
function Test(newConfig) {
if(new.target){
if(Test2 !== undefined){
console.log(new.target === Test2);// why does this give false
console.log(new.target === Test);// why does this give true
}
let mergedConfig = {};
Object.assign(mergedConfig, newConfig || {}, new.target.config || {})
let fn = Test.bind({config: mergedConfig});
fn.config = mergedConfig;
return fn;
} else {
// do something with this.config
return this.config.a + this.config.b;
}
}
// initial configuration
// the first time I'm calling the Test function, so new.target === Test
var Test2 = new Test({
a: 'a'
});
// further configuration
// the second time I'm calling the Test2 function.
// Now, new.target !== Test2, but new.target === Test.
// This is what seems weird to me.
let Test3 = new Test2({b: 'b'});
// normal call
// new.target === undefined
let result = Test3();