日期:2014-05-16  浏览次数:20319 次

大家看一下这个函数输出什么结果
function Person(name, age) {  
  this.name = name;
  this.age = age;
  this.friends = ["hello", "test"];
  }
  Person.prototype = {  
  constructor:Person,
  sayName: function() {
  alert(this.name);
  }

  }
  var person1 = new Person("wang", 32);
  alert(person1.sayName());

------解决方案--------------------
JScript code

function Person(name, age) {   
  this.name = name;
  this.age = age;
  this.friends = ["hello", "test"];
  }
  Person.prototype = {   
  constructor:Person,
  sayName: function() {
  alert(this.name);
  }

  }
  var person1 = new Person("wang", 32);
  alert(person1.sayName());//先弹出'wang',再弹出undefined,弹出undefined是因为person的sayName方法没有返回值
  person1.sayName();

------解决方案--------------------
第一次输出wang // 构造函数
第二次输出undefined //sayName无返回值,所以alert的结果是undefined