在Javascript中创建预定义对象的实例 [英] Creating instances of predefined objects in Javascript
问题描述
我知道在Javascript中我们可以创建对象的实例,如
I know that in Javascript we can create ,instatnces of object like
var ins = new myObject();
我知道,窗口,文档等是javascript中的预定义对象。我们可以创建新的实例这些对象。?
例如:
是
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();
可能吗?
推荐答案
不要将对象与构造函数(或大多数OOP语言中的类)混淆。在JavaScript中,您可以通过使用 new
运算符调用构造函数来创建对象:
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();
然后你可以使用构造函数访问给定对象的构造函数
property:
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();
在你的情况下,你可以尝试使用内置对象,但它可能会由于脚本引擎可能禁止它,因此无法正常工作。例如,当尝试使用 new document.constructor()
创建新文档时,Chrome将抛出 TypeError:Illegal constructor
。这是因为 document
的构造函数 HTMLDocument
不能直接使用。
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.
这篇关于在Javascript中创建预定义对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!