为什么在JavaScript是一个函数考虑的构造函数和对象? [英] Why in JavaScript is a function considered both a constructor and an object?

查看:147
本文介绍了为什么在JavaScript是一个函数考虑的构造函数和对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在做很多研究,但还没有得到一个很好的坚实的答案。我读到某个地方,当JavaScript引擎遇到一个函数语句时,创建一个新的Function()对象,这将导致我相信它可能是一个对象的孩子(从而成为一个)。所以我给Douglas Crockford发电子邮件,他的回答是:

I have been doing a lot of research on this lately, but have yet to get a really good solid answer. I read somewhere that a new Function() object is created when the JavaScript engine comes across a function statement, which would lead me to believe it could be a child of an object (thus becoming one). So I emailed Douglas Crockford, and his answer was:


不完全是,因为函数
语句不调用编译器。

Not exactly, because a function statement does not call the compiler.

但它产生相似的结果。

,不能在函数构造函数上调用成员,除非它已被实例化为一个新对象。所以这不会工作:

Also, to my knowledge, you can't call members on a function constructor unless it has been instantiated as a new object. So this will not work:

function myFunction(){
    this.myProperty = "Am I an object!";
}
myFunction.myProperty; // myFunction is not a function
myFunction().myProperty; // myFunction has no properties

但是,这将工作:

function myFunction(){
    this.myProperty = "Am I an object!";
}
var myFunctionVar = new myFunction();
myFunctionVar.myProperty;

这只是语义的问题...在整个编程世界中,对象真的成为一个对象,并且如何映射到JavaScript?

Is this just a matter of semantics... in the whole of the programming world, when does an object really become an object, and how does that map to JavaScript?

推荐答案


$ b

Your understanding is wrong:

myFunction().myProperty; // myFunction has no properties

它不工作的原因是因为.myProperty返回值myFunction(),而不是对象myFunction。机智:

The reason it does not work is because ".myProperty" is applied to the returned value of "myFunction()", not to the object "myFunction". To wit:

$ js
js> function a() { this.b=1;return {b: 2};}
js> a().b
2
js> 

记住,()是一个运算符。 myFunction与myFunction()不同。你不需要一个返回instanciang与新:

Remember, "()" is an operator. "myFunction" is not the same as "myFunction()". You don't need a "return" when instanciang with new:

js> function a() { this.b=1;}
js> d = new a();
[object Object]
js> d.b;
1

这篇关于为什么在JavaScript是一个函数考虑的构造函数和对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆