当前位置: 首页 > news >正文

js继承方式讲解

类分为 私有属性 公有属性 静态方法

使用对象方式,继承公有属性

let obj2 = {
   age: 9,
   name:'jw'
};
let obj = {
  name:'zfpx',
  getPName(){ // 可以通过super关键字获取到父属性
    return super.name
  },
  __proto__:obj2
}
console.log(obj.getPName());
复制代码

只继承公有属性

Child.prototype.__proto__ = Parent.prototype;
复制代码
Object.setPrototypeOf(Child.prototype, Parent.prototype)
复制代码

上面两个等价,一个是es5一个是es6

只继承共有属性

Child.prototype = Object.create(Parent.prototype,{constructor:{value:Child}});
let child = new Child;
child.smoking();
console.log(child.constructor);
复制代码

实现原理:

function create(parentPrototype,props){
  function Fn() {}
  Fn.prototype = parentPrototype;
  let fn = new Fn();
  for(let key in props){
    Object.defineProperty(fn, key, {
      ...props[key],
      enumerable:true  //不加这句枚举不出来child.constructor(undefined)
    });
  }
  return fn;
}
// defineProperty中加了set get就不能加 writable和value了。
Child.prototype = create(Parent.prototype,{constructor:{value:Child}});
let child = new Child();
console.log(child.constructor);
复制代码

只继承私有属性 再子类中调用父类的方法即可 Parent.call(this)

function Parent(){
    this.parent = 'parent';
}
Parent.prototype.smoking = function () {
    console.log('吸烟')
}
function Child(){
    Parent.call(this)
}
console.log(new Child().parent)
复制代码

child继承父类的所有的属性

function Parent(){
    this.parent = 'parent';
}
Parent.prototype.smoking = function () {
    console.log('吸烟')
}
function Child(){}
 Child.prototype = new Parent;
let child = new Child();
Child.prototype.eat = function () {
 console.log('吃')
 }
 console.log(child.parent)
 console.log(child.smoking)
 child.__proto__.eat();
 console.log(child.__proto__=== Child.prototype)
 console.log(Child.prototype.constructor === Child)
复制代码

为了追本溯源, 我顺便研究了new运算符具体干了什么?发现其实很简单,就干了三件事情.

var obj  = {};
obj.__proto__ = F.prototype;
F.call(obj);
复制代码

第一行,我们创建了一个空对象obj;

第二行,我们将这个空对象的proto成员指向了F函数对象prototype成员对象;

第三行,我们将F函数对象的this指针替换成obj,然后再调用F函数.

我们可以这么理解: 以 new 操作符调用构造函数的时候,函数内部实际上发生以下变化:

1、创建一个空对象,并且 this 变量引用该对象,同时还继承了该函数的原型。

2、属性和方法被加入到 this 引用的对象中。

3、新创建的对象由 this 所引用,并且最后隐式的返回 this

function Otaku (name, age) {
    this.name = name;
    this.age = age;

    this.habit = 'Games';
}

Otaku.prototype.strength = 60;

Otaku.prototype.sayYourName = function () {
    console.log('I am ' + this.name);
}

// 模拟new
function objectFactory() {

    var obj = new Object(),

    Constructor = [].shift.call(arguments);

    obj.__proto__ = Constructor.prototype;

    var ret = Constructor.apply(obj, arguments);//对返回指值做处理,如果是引用对象则返回对象,如果是基本类型则忽略返回值,依然返回对象obj

    return typeof ret === 'object' ? ret : obj;

};

var person = objectFactory(Otaku, 'Kevin', '18')

console.log(person.name) // Kevin
console.log(person.habit) // Games
console.log(person.strength) // 60

person.sayYourName(); // I am Kevin
复制代码

es6中的class继承公有属性和私有属性和静态方法

class Child extends Parent{ // 要求继承父亲的私有和有公有
  constructor(){
    super(); // Parent.call(this);
    this.age = 9; // 私有属性
  }
  static a(){ // 属于类上的方法
    return 1;
  }
  smoking(){ // 原型上的方法
    console.log('smoking')
  }
}
let child = new Child();
复制代码

转载于:https://juejin.im/post/5b09469af265da0dcd0b6648

相关文章:

  • BZOJ5286:[HNOI/AHOI2018]转盘——题解
  • maven 下载地址
  • JS中的深拷贝与浅拷贝了解一下
  • Postfix邮件系统
  • .NET CORE 2.0发布后没有 VIEWS视图页面文件
  • MSSQL最佳实践:如何监控备份还原进度?
  • 项目依赖和生成顺序造成的问题
  • MySQL修改root密码的方法
  • 多线程事务回滚
  • 5.30 Tree Traversal + Tree manipulation
  • 网页视频加速播放
  • 阿里云新一代关系型数据库 PolarDB 剖析
  • 函数模板(四十七)
  • Springboot 整合 dubbo 的一些坑
  • 10 个 Python 初学者必知编码小技巧
  • [译]CSS 居中(Center)方法大合集
  • ➹使用webpack配置多页面应用(MPA)
  • iOS动画编程-View动画[ 1 ] 基础View动画
  • JAVA 学习IO流
  • java中具有继承关系的类及其对象初始化顺序
  • uni-app项目数字滚动
  • 分布式事物理论与实践
  • 计算机常识 - 收藏集 - 掘金
  • 开源SQL-on-Hadoop系统一览
  • 全栈开发——Linux
  • 深入 Nginx 之配置篇
  • 微信开源mars源码分析1—上层samples分析
  • 以太坊客户端Geth命令参数详解
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • # 数据结构
  • # 再次尝试 连接失败_无线WiFi无法连接到网络怎么办【解决方法】
  • (1)Map集合 (2)异常机制 (3)File类 (4)I/O流
  • (Java岗)秋招打卡!一本学历拿下美团、阿里、快手、米哈游offer
  • (ZT)出版业改革:该死的死,该生的生
  • (转)MVC3 类型“System.Web.Mvc.ModelClientValidationRule”同时存在
  • (转)大道至简,职场上做人做事做管理
  • .dwp和.webpart的区别
  • .NET CORE 3.1 集成JWT鉴权和授权2
  • .NET Core、DNX、DNU、DNVM、MVC6学习资料
  • .NET Core引入性能分析引导优化
  • .NET/C# 解压 Zip 文件时出现异常:System.IO.InvalidDataException: 找不到中央目录结尾记录。
  • .net2005怎么读string形的xml,不是xml文件。
  • .Net的DataSet直接与SQL2005交互
  • .net反编译工具
  • :O)修改linux硬件时间
  • [AHOI2009]中国象棋 DP,递推,组合数
  • [AIGC] 如何建立和优化你的工作流?
  • [AutoSar]BSW_Memory_Stack_004 创建一个简单NV block并调试
  • [CF482B]Interesting Array
  • [cogs2652]秘术「天文密葬法」
  • [CQOI 2010]扑克牌
  • [GXYCTF2019]BabySQli1
  • [iOS]中字体样式设置 API
  • [JavaEE]线程的状态与安全
  • [LOJ#6259]「CodePlus 2017 12 月赛」白金元首与独舞