ESS下继承关系

一 概念
ES5 ```js // 父级 function Sup(name) { this.name = name; this.fn = function () { console.log('fn class'); } } // 原型 console.log(Sup.prototype); console.log(sup.__proto__); // 子级 function Sub(name) { // 继承属性 Sup.call(this, name); } // 继承方法 Sub.prototype = new Sup; // 创建子级对象 var sub = new Sub("subClass"); // 使用属性 console.log(sub.name); // 使用方法 sub.fn(); // 指向自身构造函数 Sub.prototype.constructor = Sub;

类及继承ES6
```js
// 父类
class People {
    // 构造器
    constructor (name, age) {
        this.name = name;
        this.age = age;
    }
    // 实例方法
    eat () {
        console.log('吃吃吃');
    }
    // 类方法
    static create () {
        console.log('诞生');
    }
}
// 子类
class Student extends People {
    constructor (name, age) {
        // super关键词
        super(name, age)
    }
}
```
二 代码示范

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>ES5下继承关系</title>
</head>
<body>

</body>
<script type="text/javascript">
// ***
// 面向对象的三大特性: 继承 封装 多态

// js重点:继承

// 1.完成继承,必须拥有两个构造函数
// 2.一个函数要使用另外一个函数的属性与方法,需要对其进行继承(属性与方法的复用)
// 3.属性的继承call方法,在继承函数中由被继承函数调用,传入继承函数的this与被继承函数创建属性对属性进行赋值的所有需要的数据,eg:如Sup有name属性,那么可以通过call将Sub的name传给Sup
// 4.方法的继承prototype原型,将new Sup赋值给Sub.prototype

// 类似于父级
function Sup(name) {
// 属性存放某个值
this.name = name;
// 方法完成某项功能
this.func = function () {
console.log("func");
}
}
var sup = new Sup("supClass");
console.log(sup.name);
sup.func();

// 类似于子级
function Sub(name) {
// 属性的继承
Sup.call(this, name);
}
// 方法的继承
Sub.prototype = new Sup;

var sub = new Sub("subClass");
console.log(sub.name);
sub.func();

// 原型
console.log(sup.__proto__);

</script>
</html>



posted @ 2018-10-16 15:51  不沉之月  阅读(88)  评论(0编辑  收藏  举报