Problem
var a = someName().LogEmergency('my error');
a
is referring to the global object and not the object you think you have created(which is window
if you are running this code in a browser)
console.log(a === window)
--> will be true.
your final result is wrong because you are comparing with the wrong object.if you are wondering why, that's because you were missing the keyword new
while creating the object.
calling a function with new triggers the constructor mechanism that creates a new object and returns it.
calling a function without new and returning "this" inside a function returns the global object.
you have to make the following changes to your code
var someName = function(){
this.LogEmergency = function(message){
this.message = message;
return this; // here this refers to the new object you created
};
return this; // here also this refers to the new object you created
// here the return is redundant as this is implicit.
};
// new operator is the keyword for creating objects.
// the meaning of "this" inside the function completely changes without the operator
var a = new someName().LogEmergency('my error');
in the above code a
now refers to the new instance you created.
finally check if the created object is an instance of someone
console.log(a instanceof someName); //will be true
Read more about constructors here