最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why doesn't `{}.toString.apply(array)` work? - Stack Overflow

programmeradmin4浏览0评论

Usually, when I want to check the type of an object (whether it's an array, a NodeList, or whatever), I use the following:

var arr = [] // I don't do this, but it's for the sake of the example
var obj = {}
obj.toString.apply(arr) // This works

The question is: why can I not do the following?

var arr = []
{}.toString.apply(arr) // Syntax error: Unexpected token .

I don't get where the syntax error is.

I can do something approaching with [] though, the following works:

var nodeList = document.getElementsByClassName('foo')
[].forEach.call(nodeList, function(bar) { console.log(bar) }) // Works

So... I'm confused.

Usually, when I want to check the type of an object (whether it's an array, a NodeList, or whatever), I use the following:

var arr = [] // I don't do this, but it's for the sake of the example
var obj = {}
obj.toString.apply(arr) // This works

The question is: why can I not do the following?

var arr = []
{}.toString.apply(arr) // Syntax error: Unexpected token .

I don't get where the syntax error is.

I can do something approaching with [] though, the following works:

var nodeList = document.getElementsByClassName('foo')
[].forEach.call(nodeList, function(bar) { console.log(bar) }) // Works

So... I'm confused.

Share Improve this question edited Apr 4, 2012 at 7:07 Florian Margaine asked Apr 4, 2012 at 7:00 Florian MargaineFlorian Margaine 60.9k15 gold badges93 silver badges120 bronze badges 3
  • you forgot () in toString() ? – kappa Commented Apr 4, 2012 at 7:02
  • Nope, see @Ray Toal's answer. Adding the parenthesis would lead to a syntax error (Object has no method 'apply'). – Florian Margaine Commented Apr 4, 2012 at 7:13
  • Ahh.. i didn't thought that, it's correct – kappa Commented Apr 4, 2012 at 7:19
Add a ment  | 

1 Answer 1

Reset to default 16

When you begin a line with { JavaScript thinks it starts a block statement, not an object literal. Parenthesize it and you will be okay.

发布评论

评论列表(0)

  1. 暂无评论