创建对象实例时不会显示控制台日志记录

时间:2013-06-17 02:13:00

标签: javascript

代码段1:

<script>
function Person(lastName, firstName){ 
  this.lastName = lastName; 
  this.firstName = firstName; 
}
var DnnyGdmn = new Person("Goodman","Danny"); 
var DvdFlngn = new Person("Flanagan","David"); 
function Book(title, pages, price){ 
  this.title = title; 
  this.pages = pages; 
  this.price = price; 
  this.authors = new Array(arguments.length-3);
  console.log(arguments);
  for(i = 0; i < arguments.length - 3; i++){ 
    this.authors[i] = arguments[i + 3]; 
  } 
}
var JavaNut = new Book("Java Foundation Classes in a Nutshell", 731, 29.95, DvdFlngn); 
var JSTDR = new Book("Javascript: The Definitive Guide (3rd  Edition)", 776, 39.95, DvdFlngn); 
</script>

在Firefox firebug-&gt; console-&gt; all中,我看到了:

["Java Foundation Classes in a Nutshell", 731, 29.95, Person { lastName="Flanagan", firstName="David"}]
["Javascript: The Definitive Guide (3rd Edition)", 776, 39.95, Person { lastName="Flanagan", firstName="David"}] 

代码段2:

<script>
function Person(lastName, firstName){ 
  this.lastName = lastName; 
  this.firstName = firstName; 
}
var DnnyGdmn = new Person("Goodman","Danny"); 
var DvdFlngn = new Person("Flanagan","David"); 
</script>

在Firefox firebug-&gt; console-&gt; all中,它没有显示任何内容。

问题:

两个代码片段都做同样的事情,创建某个对象的实例,但是为什么1写一些东西到控制台,而代码2没有呢?

1 个答案:

答案 0 :(得分:3)

codes 1中,你有这个:

console.log(arguments);

这可以在这里找到:

  ...
  this.pages = pages;
  this.price = price;

  this.authors = new Array(arguments.length-3); console.log(arguments);

  for(i=0;i<arguments.length-3;i++){
    this.authors[i] = arguments[i+3];
  }
  ...

此代码将参数值写入console。由于代码不在codes 2中,因此它不会在控制台中输出任何内容。