Javascript:构造对象 [英] Javascript: Constructing Objects

查看:89
本文介绍了Javascript:构造对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个javascript noob,但我有一个一直困扰我的一般性问题。让我们举个例子:

I'm a bit of a javascript noob, but I have a general question that has been bothering me. Lets take an example:

如果我在Chrome上跳进JS控制台,我可以轻松浏览窗口对象。 window 似乎列出了很多类类型,可以这么说。例如, window.CSSPrimitiveValue 就是这样一个属性。当我在控制台中评估 window.CSSPrimitiveValue 时,我会回到看起来像构造函数的东西(可能):

If I hop into a JS console on Chrome, I can easily browse the window object. window seems to list a lot 'class types', so to speak. For example, window.CSSPrimitiveValue is one such property. When I evaluate window.CSSPrimitiveValue in the console, I get back what looks like a constructor (possibly):

function CSSPrimitiveValue() { [native code] }

所以它看起来这个函数是用某种母语实现的。不管。当然,我想构建其中一个,如下所示:

So it looks like the function was implemented in some native language. No matter. Naturally, I want to construct one of these things, like so:

var test = new CSSPrimitiveValue();

然后我收到错误:

TypeError: Illegal constructor

我怀疑我要么打电话构造函数不正确,或者它根本不是构造函数。我是一个相当大的JS noob关于这个,但有没有办法让我手动构建这些对象之一?有什么方法可以解决这个问题?

I suspect that either I am calling the constructor incorrectly, or it isn't a constructor at all. I'm a pretty big JS noob about this, but is there any way for me to manually construct one of these objects? What would be the method to going about that?

推荐答案

使用JavaScript编写的任何用JavaScript编写的函数都可以是构造函数关键字。正如您已经注意到,您正在处理的函数是 native ,即用C或C ++编写(可能是C ++,因为Chrome的JavaScript引擎也是用C ++编写的)。本机函数/对象可以具有特定的行为,例如你不能将它用作构造函数的情况 - 你无能为力。

Any function that is written in JavaScript can be a constructor when called using the new keyword. As you already noticed the function you are dealing with is native, i.e. written in C or C++ (probably C++ since Chrome's JavaScript engine is written in C++, too). Native functions/objects can have specific behaviour such as your case where you cannot use it as a constructor - there's nothing you can do.

这个函数甚至没有有一个 .call()方法,你也不能在你之前创建的对象上调用它(不是因为它没有正确的它会非常有用[ [原型]]设置)

That "function" doesn't even have a .call() method, you you also cannot call it on an object you created before (not that it would be very useful as it wouldn't have the proper [[Prototype]] set)

这篇关于Javascript:构造对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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