当前位置:编程学习 > JS >>

关于JS的错误

我的代码如下:

<script language="javascript">
function Person(name, age){
 this.name = name;
  this.age = age;
 this.say = sayFunc();
}
 
  function sayFunc(){
       alert(this.name+ ":" +this.age);
 }


var person1 =new Person("张三",18);
person1.say();             
</script>

运行结果this.name为空,this.age未定义

请问错在哪里?

追问:那要怎么改才正确?

答案:<script language="javascript">
 function Person(name,age){
  this.name = name;
  this.age = age;
  this.say = function(){
   alert(this.name + ":" + this.age);
  };
 }

 var person = new Person("张三",18);
 person.say();
</script>

  function sayFunc(){
       alert(this.name+ ":" +this.age);
 }
这个方法里面没有name,age要给sayFunc()方法带上参数sayFunc(name,age)才能传进来

this.name是批量sayFunc的name和age,所以会出错

我修改了一下:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
</body>
</html>
<script language="javascript">
function Person(name, age){
 this.name = name;
  this.age = age;
  this.say = function(){sayFunc(this.name,this.age)};
}
 
  function sayFunc(name,age){
       alert(name+ ":" +age);
 }


var person1 =new Person("张三",18);
person1.say()            
</script>

上一个:js 能截取字符串
下一个:JS截取字符串问题

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,