对象自然功能 [英] Object-Natured Functions
问题描述
我注意到一些函数只能用 new
前缀。在没有它的情况下调用时,会抛出错误 Illegal Invocation 。下面是以不同方式调用 Image
时控制台如何响应的两个示例。
- >新图片();
< - < img>
- >图片();
< - TypeError:DOM对象构造函数不能作为函数调用。
更有趣的是,在仔细观察下,这些类型的函数看起来像函数,但它们不是。以 Image
为例, typeof
命令显示 Image
是的构造函数的一个函数,Image
意味着它是一个Object。
这与大多数构造函数如下所示。
function Foo(){
this.identity ='Bar';
$ / code>
函数 Foo
可以被称为两种方式,新的Foo()
和 Foo()
。这与 Image
函数非常不同。
问题
与 Image
函数的这个动作与大多数构造函数完全不同。这怎么可能?这是为什么 new
前缀必须与 Image
一起使用?更重要的是,这种类型的函数可以被重新创建吗?
我认为这是您寻找的逻辑重现当 new
关键字未用于创建 Foo
的实例时发生异常:
function Foo(){
if(!(this instanceof arguments.callee))
throw new TypeError(DOM object constructor can not be称为函数。);
this.identity ='Bar';
}
根据这篇文章,而不是 arguments.callee
如果您处于严格模式,请使用函数名称 Foo
:
函数Foo(){
if(!(this instanceof Foo))
throw new TypeError(DOM object constructor can not be called as a function。);
this.identity ='Bar';
}
查看 DEMO here ,它说明了这种情况。
Context
I've noticed that some functions can only be called with the new
prefix. When called without it, the error Illegal Invocation is thrown. Below is two examples of how the console reacted when the Image
was called in different ways.
-> new Image();
<- <img>
-> Image();
<- TypeError: DOM object constructor cannot be called as a function.
Even more interesting, under closer observation, these types of functions seem like functions, yet they aren't. Take Image
for example, the typeof
command reveals that Image
is a function yet the constructor of Image
implies that it is an Object.
This is very different than most construction functions like the one below.
function Foo(){
this.identity = 'Bar';
}
The function Foo
can be called two ways, new Foo()
and Foo()
. This is very different than the Image
function.
The Question
This action with the Image
function is very different than most construction functions. How is this possible? Is this why the new
prefix must be used with Image
? And more importantly can this type of function be recreated?
I think this is the logic you're looking for that reproduces the exception when the new
keyword isn't used to create an instance of Foo
:
function Foo() {
if (!(this instanceof arguments.callee))
throw new TypeError("DOM object constructor cannot be called as a function.");
this.identity = 'Bar';
}
According to some comments in this post, instead of arguments.callee
you'd have to use the function name Foo
if you are in strict mode:
function Foo() {
if (!(this instanceof Foo))
throw new TypeError("DOM object constructor cannot be called as a function.");
this.identity = 'Bar';
}
See a DEMO here that illustrates the situation.
这篇关于对象自然功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!