I know that in Javascript we can create ,instatnces of object like
var ins = new myObject();
I know that ,window ,document etc are predefined objects in javascript..Can we create new instances of these objects.?
For ex:
Is
var inss = new document();
possible?
Yes and no, mostly no.
You can create a new
window
object usingwindow.open
. It will also have a newdocument
object.You can create a new DOM
document
viacreateDocument
, though it won't necessarily have all the special features of the pre-made one. You can also create a new document fragment viacreateDocumentFragment
, which can be very handy.document
is not a constructor, it's a constructed object. What you are trying to do is like sayingnew new Object()
ornew {}
.The constructor of
document
isHTMLDocument
but you cannot construct it that way, you must usedocument.implementation.createDocument()
Don't confuse objects with constructors (or classes in most OOP languages). In JavaScript, you create objects by calling constructor functions using the
new
operator:Afterwards you can access the constructor given the object using the
constructor
property:Theoretically, you can create new objects of the same type as a given object:
In your case, you might try the same with "built-in" object, but it will probably not work since the script engine might forbid it. For example, Chrome will throw
TypeError: Illegal constructor
when trying to create a new document usingnew document.constructor()
. This is becausedocument
's constructor,HTMLDocument
, is not meant to be used directly.The new operator only works with objects that are user defined, or built-ins that have a constructor. document and window don't have constructors.
No, you can't. Although most of these host objects have constructors (e.g.
HTMLDocument
fordocument
), they are only used for inheritance feautures (e.g. theinstanceof
operator) but can not be invoked.You also can't create
Node
s for example, these "constructors" are just interfaces.Yet, you can create a new DOM with the
createDocument
method, which is available at thedocument.implementation
object.