父类:
//构造
function User(userName,age){
this.userName = userName;
this.age = age;
}
//方法
User.prototype = {
//反向回调
constructor : User,
toString : function(){
return this.getUserName()+','+this.getAge();
},
setUserName : function(userName){
this.userName = userName;
},
getUserName : function(){
return this.userName;
},
setAge : function(age){
this.age = age;
},
getAge : function(){
return this.age;
}
}
子类:
//构造
function Student(no){
this.no = no;
}
//继承
Student.prototype = inherit(User.prototype);
extend(Student.prototype,
{
//重写
setAge : function(age){
this.age = age+1;
},
//重写
toString : function(){
return 'the NO. is: '+this.no+',the name is: '+this.getUserName()+',the age is: '+this.getAge();
},
//自身方法
getNo : function(){
return this.no;
}
}
);
//继承
function inherit(p){
if(p == null) throw TypeError();
//对象
if(Object.create){
return Object.create(p);
}
//方法
var t = typeof p;
if(t !== 'Object' && t !== 'function') throw TypeError();
function f(){};
f.prototype = p;
return new f();
}
//扩展
function extend(o,p){
for(prop in p){
o[prop] = p[prop]
}
return o;
}
//使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>继承</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="QZJ">
<script type="text/javascript" src="User.js"></script>
<script type="text/javascript" src="Student.js"></script>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<script>
$().ready(function(){
var user = new User('qzj','123456');
console.log('log',user.toString());
user.setUserName('qzj');
console.log('log',user.toString());
var stu = new Student(123);
stu.setUserName('qzjHahaha');
stu.setAge(12);
console.log('log',stu.toString());
console.log('log',stu.getNo());
});
</script>
<body>
</body>
</html>