/*
以下是个简单的继承的例子
就是Student继承了Person
*/
function Person(name,sex){
this.name = name;
this.sex = sex;
};
Person.prototype = {
setName:function(name){
this.name = name;
},
getName:function(){
return this.name;
},
setSex:function(sex){
this.sex = sex;
},
getSex:function(){
return this.sex;
}
};
function Student(name,sex,age){
Person.call(this,name,sex);
this.age = age;
};
Student.prototype = new Person();
Student.prototype.setAge = function(age){
this.age = age;
};
Student.prototype.getAge = function(){
return this.age;
};
/*
首先我们需要了解的是继承的本质
继承的期望是子类能够拥有父类的所有的属性和方法
并且,当父类被修改,或者新增方法之后
子类也能跟着变
但是如果子类被修改,父类还是保持不变。
然后开始分享我的一些理解
*/
/* 1.类的定义的时候是否使用prototype来定义类的方法或者属性 */
/*
Person这个类的方法还可以这么定义
*/
function Person(name,sex){
this.name = name;
this.sex = sex;
var setName = function(name){
this.name = name;
};
};
Person.prototype = {
getName:function(){
return this.name;
},
setSex:function(sex){
this.sex = sex;
},
getSex:function(){
return this.sex;
}
};
/*
如果这么定义的话就会发生一个问题,就是Student在继承setName之后
如果修改Person的setName方法,那么Student获取不到最新的setName方法
但是使用prototype来设置的setName方法,后面再修改setName方法
Student是可以获取到最新的setName方法的。
这个大家可以自己去尝试下
还有一些其他的问题,一时想不起来了,慢慢的加一下,有谁也有一些问题,告诉我,我一起加进来
*/