当前位置: 代码迷 >> JavaScript >> 大家看一上这个函数输出什么结果
  详细解决方案

大家看一上这个函数输出什么结果

热度:281   发布时间:2012-09-24 13:49:41.0
大家看一下这个函数输出什么结果
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
  相关解决方案