设为首页 加入收藏

TOP

js重新讲解继承,es5的一些继承,es6继承的改变 ----------由浅入深
2017-10-10 12:41:29 】 浏览:363
Tags:重新 讲解 继承 es5 一些 es6 改变 ---------- 由浅入深

es5 利用原型公有私有继承

function Parent(name) {
    this.name = name
}
Parent.prototype.home = '北京';
function Child() {
    this.age = 8;
}
//将父类的实例绑定在子类的原型上
Child.prototype = new Parent('aa');
//实例化原型
let child = new Child();
//这时候继承父类的公有私有属性
console.log(child.home+child.name);
// 结果 北京 + aa

es5 私有继承,改变this指向,公有不继承

 
  

function Parent(name) {
this.name = name
}
//父类的公有属性
Parent.prototype.home = '北京';

 
  

function Child(name) {
this.age = 8;
Parent.call(this,...arguments);

 
  

}
let child = new Child('hello');
console.log(child.home+child.name);
//结果是 undefined +hello

 

es5继承公有属性,私有属性不继承

function Parent(name) {
    this.name = name
}
Parent.prototype.home = '北京';
function Child() {
    this.age = 8;
}
Child.prototype = Object.create(Parent.prototype);
let child = new Child();
//这时候继承只继承父类的公有属性 父类的私有属性没有继承
console.log(child.home+child.name);
// 结果 北京 + indefined

 

es6 继承,私有公有都继承extend//定义一个类

class Person { //控制器
 constructor(name,age){ this.name=name; this.age=age; } eat(){ console.log("吃饭"); } } //只继承共有的

//关键字 extends 公私有都会继承
class Girl extends Person{ constructor(name,age){ super(name,age); //默认调用父类,并且this就是girl实例
 } } let g=new Girl('aa',18); console.log(g.name,g.age); g.eat();
//结果
aa 18

//
吃饭
 

 node继承  利用util模块  

inherits

function Parent(name) {
    this.name = name
}
Parent.prototype.home = '北京';
function Child() {
    this.age = 8;
}
// es5 里面判断数据类型
// indexof
// instanceof
// constuctor
// Object.prototype.toString.call

//util 判断数据类型
console.log(util.isArray({}));
//继承使用util里的方法 inherits
util.inherits(Child,Parent);

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇事件对象(示例、封装函数EventUt.. 下一篇es6异步编程 Promise 讲解 ------..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目