I'm a bit of a javascript noob, but I have a general question that has been bothering me. Lets take an example:
If I hop into a JS console on Chrome, I can easily browse the window
object. window
seems to list a lot 'class types', so to speak. For example, window.CSSPrimitiveValue
is one such property. When I evaluate window.CSSPrimitiveValue
in the console, I get back what looks like a constructor (possibly):
function CSSPrimitiveValue() { [native code] }
So it looks like the function was implemented in some native language. No matter. Naturally, I want to construct one of these things, like so:
var test = new CSSPrimitiveValue();
But then I get an error:
TypeError: Illegal constructor
I suspect that either I am calling the constructor incorrectly, or it isn't a constructor at all. I'm a pretty big JS noob about this, but is there any way for me to manually construct one of these objects? What would be the method to going about that?
I'm a bit of a javascript noob, but I have a general question that has been bothering me. Lets take an example:
If I hop into a JS console on Chrome, I can easily browse the window
object. window
seems to list a lot 'class types', so to speak. For example, window.CSSPrimitiveValue
is one such property. When I evaluate window.CSSPrimitiveValue
in the console, I get back what looks like a constructor (possibly):
function CSSPrimitiveValue() { [native code] }
So it looks like the function was implemented in some native language. No matter. Naturally, I want to construct one of these things, like so:
var test = new CSSPrimitiveValue();
But then I get an error:
TypeError: Illegal constructor
I suspect that either I am calling the constructor incorrectly, or it isn't a constructor at all. I'm a pretty big JS noob about this, but is there any way for me to manually construct one of these objects? What would be the method to going about that?
Share Improve this question edited Mar 25, 2014 at 7:38 Cjxcz Odjcayrwl 22.8k42 gold badges149 silver badges230 bronze badges asked Mar 30, 2012 at 21:53 BenBen 7,80215 gold badges51 silver badges64 bronze badges 1- In some cases I was able to create my own object that has the same properties and methods as the object I wasn't allowed to create and it worked. – The Muffin Man Commented Nov 4, 2016 at 19:41
1 Answer
Reset to default 21Any function that is written in JavaScript can be a constructor when called using the new
keyword. As you already noticed the function you are dealing with is native, i.e. written in C or C++ (probably C++ since Chrome's JavaScript engine is written in C++, too). Native functions/objects can have specific behaviour such as your case where you cannot use it as a constructor - there's nothing you can do.
That "function" doesn't even have a .call()
method, you you also cannot call it on an object you created before (not that it would be very useful as it wouldn't have the proper [[Prototype]] set)