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

Js中一个关于prototype的问题!!

function Person(name) {
this.name = name;
}
Person.prototype.say = function() {
alert('I"m ' + this.name);
}
function Son(name, age) {
Person.call(this, name);
this.age = age;
this.showage = function() {
alert('I"m ' + this.age + 'years old');
}
}

var p = new Person('koma');
p.say();
var s = new Son('csdn', 15);
s.say();                    //这里提示方法不存在
s.showage();


对于上面那个报错的问题,不知道大家有什么看法??

另外,我是看李战大哥的吾透javascript这本书上的代码敲的,但是就是报错了。。。

------解决方案--------------------
<!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>
<script type="text/javascript">
function Person(name) {
    this.name = name;
}
Person.prototype.say = function() {
    alert('I"m ' + this.name);   
}
function Son(name, age) {
    Person.call(this, name);
    this.age = age;
    this.showage = function() {
        alert('I"m ' + this.age + 'years old');   
    }
}
Son.prototype=new Person(); 
var p = new Person('koma');
p.say();   
var s = new Son('csdn', 15);
s.say();                    //这里提示方法不存在
s.showage();
</script>
</head>

<body>
</body>
</html>
Person.call(this, name);只是调用Person函数 把this指向子类的对象 所以子类原型里是没say方法的  貌似
------解决方案--------------------
是的  他只是将父类的this指向子类的对象而已
------解决方案--------------------
function Person(name) {
if(typeof name != 'undefined'){
this.name = name;
}
    
}
Person.prototype.say = function() {
   &n