typeof(function.arguments)是对象

时间:2013-12-18 16:18:57

标签: javascript

让我们有一个简单的功能

make=function(){ }

为什么当我们尝试显示alert(Object.getOwnPropertyNames(make.arguments));时出现错误

[18:33:06.588] TypeError: make.arguments is not an object @ http://fiddle.jshell.net/_display/:28

但是

alert(typeof(make.arguments));

显示object

2 个答案:

答案 0 :(得分:3)

如果typeof X返回"object",则并不表示X是对象。

您提供的make.arguments属性代码为null,根据ECMAScript规范部分11.4.3 typeof null返回"object"

所以你隐含地执行以下代码:Object.getOwnPropertyNames(null),结果会抛出TypeError异常。

答案 1 :(得分:0)

如果您要做的只是获取传递给函数的参数,则以下内容就足够了:

function test () {
   console.log(arguments) // Appears to be an array '[]'.
}

让我们来看看类型:

function test () {
   console.log(arguments instanceof Array) // False. It's an object.
}

事实证明,参数根本不是一个数组,需要一些技巧:

function test () {
   var args = [].slice.call(arguments); 
   console.log(args instanceof Array) // True. It's an array.
   console.log(typeof args) // Object. Sigh.
}

我所提出的观点(并且由VisionN更好地解释)是,typeof的工作方式如下:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

看看桌子。 Null AND参数(它是一个对象)将是'object'类型,因为它将清空数组。