类的创建
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
class Person{
constructor(name,age) {
this.name=name;
this.age=age;
}
say(x){
console.log(this.name+',我在说话,'+x);
}
}
var p1=new Person('小谷',10);
console.log(p1);
p1.say(10);
</script>
</html>
新的继承方式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
class Father{
constructor(name,age) {
this.name=name;
this.age=age;
}
say(){
console.log('我调用了父亲的say');
}
}
class Son extends Father{
sleep(){
console.log('我在睡觉');
}
}
var son1=new Son('小谷',10);
son1.sleep();
son1.say();
console.log(son1);
function Father2 () {
this.run=function(){
console.log('父亲的跑步');
}
}
function Son2(){
Father2.call(this);
}
Son2.prototype=new Father2();
Son2.prototype.constructor=Son2;
Son2.prototype.eat=function () {
console.log('孩子吃东西');
}
var son2=new Son2();
console.log('-------------');
son2.run();
son2.eat();
console.log(son2);
</script>
</html>
super关键字
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
class Father {
constructor(name, age) {
this.name = name;
this.age = age;
}
play(){
console.log('我在打孩子');
}
eat(){
console.log('我吃的是父亲的食物');
}
}
Father.prototype.shout='999';
class Son extends Father {
constructor(name, age, sex) {
super(name, age);
this.sex = sex;
this.study=function () {
console.log('我是son自身的方法,是成员属性');
}
}
say(){
console.log('我是孩子的say方法,属于原型对象的');
super.play();
console.log(super.shout);
}
eat(){
console.log('我吃的是孩子的食物');
}
}
var son = new Son('小好', 10, '女');
son.study();
son.say();
son.eat();
console.log(son);
</script>
</html>