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


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('希赛', 15);
s.say();                    //这里提示方法不存在
s.showage();



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


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


java 程序开发 JavaScript

8807012 9 years, 7 months ago

Person.call(this, name);调用过后这是给Son的实例添加了一个name的属性而已,Person原型上的say方法需要实例化对象才能添加到该对象中,你可以把这句改为son.prototype=new Person();

qieyin answered 9 years, 7 months ago

Son中的“Person.call...”只是单纯的调用函数Person,作用是给Son的实例化对象添加name属性,而say方法在Person的原型对象中,跟Person.call是毫无关系的,当然Son中也就不会有say这个方法。

himiko answered 9 years, 7 months ago

  function Person(name) {
if(typeof name != 'undefined'){
this.name = name;
}
    
}
Person.prototype.say = function() {
    alert('I"m ' + this.name);    
}
Son.prototype=new Person();
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('希赛', 15);
s.say();                    //这里提示方法不存在
s.showage();


dar@k answered 9 years, 7 months ago

是的  他只是将父类的this指向子类的对象而已

M82A3 answered 9 years, 7 months ago

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">

<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('希赛', 15);

s.say();                    //这里提示方法不存在

s.showage();

</script>

</head>


<body>

</body>

</html>

Person.call(this, name);只是调用Person函数 把this指向子类的对象 所以子类原型里是没say方法的  貌似

霧雨魔里莎 answered 9 years, 7 months ago

<fieldset> <legend class="font_bold"> 引用: </legend>

   <fieldset> <legend> Quote: 引用: </legend>

  Son中的“Person.call...”只是单纯的调用函数Person,作用是给Son的实例化对象添加name属性,而say方法在Person的原型对象中,跟Person.call是毫无关系的,当然Son中也就不会有say这个方法。

</fieldset>

那怎么样做才可以让Son中对象也具有say方法同时又不需要让父类的原型覆盖子类的原型呢?

</fieldset>


这楼盖的真快~~

楼主  我是否还有回答的必要?

月下的蝗虫 answered 9 years, 7 months ago

Your Answer