Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instances of predefined objects in Javascript

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?

like image 280
Jinu Joseph Daniel Avatar asked Feb 20 '23 16:02

Jinu Joseph Daniel


2 Answers

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:

function MyObject()
{
}

var obj = new MyObject();

Afterwards you can access the constructor given the object using the constructor property:

var ctor = obj.constructor;  // (ctor === MyObject) will be true

Theoretically, you can create new objects of the same type as a given object:

var obj1 = new MyObject();
var obj2 = new obj1.constructor();

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 using new document.constructor(). This is because document's constructor, HTMLDocument, is not meant to be used directly.

like image 88
Ferdinand Beyer Avatar answered Mar 04 '23 06:03

Ferdinand Beyer


Yes and no, mostly no.

You can create a new window object using window.open. It will also have a new document object.

You can create a new DOM document via createDocument, though it won't necessarily have all the special features of the pre-made one. You can also create a new document fragment via createDocumentFragment, which can be very handy.

like image 33
T.J. Crowder Avatar answered Mar 04 '23 06:03

T.J. Crowder