> $ = function() { > this.name = "levi"; > > return this; }; > > console.log($());
We get DOMWindow instead of $
When you call $ as funciton, then this keyword is set by the global object, as it would be for any function called like that.
due to the bizarre nature of this in javascript
Javascript is the * keyword that works as directed. It is different from other languages, but that’s how it works.
Which is weirder for me, console.log ($ (). Name) correctly returns "Levi".
When you call $ as a function, its this keyword is a global object, therefore:
this.name = 'levi';
creates a property of a global object named name with the value 'levi'. It is not strange when you know what is going on .:-)
We could just add a new console.log (new $ ()) and it works.
So it is assumed that constructors should be called in javascript. When a function is called with the name new, its this keyword is set to a new object, so this.name will create a new property for this object. By the way, return this redundant; constructors return this by default.
> $ = function() { > var obj = function() { > this.name = "levi"; > }; > > return new obj(); };
console.log ($ ()); Which gives me what I want, but it seems a little unnecessary to wrap the object inside which creates it. Further, moreover, it is type obj, not type $
Presumably you are using typeof, which can only return one of the values specified by ECMA-262. This short list (which includes an object, number, string, and so on) does not include $.
What other ways can this be done?
You can use the approach you found, a clone of Lasse Reichstein Nielsen (also popularized by Dubos Crockford as “generated”) and a sample module of Richard Kornford. Use Google, there are many, many posts about all of the above.