美文网首页
JS 中继承的写法

JS 中继承的写法

作者: 小废柴JH | 来源:发表于2019-07-20 09:49 被阅读0次

es5:

function Human(name){
  this.name = name
}

Human.prototype.move = function(){}

function Man(name){
  Human.call(this, name)
  this.gender = '男'
}

Man.prototype.__proto__ === Human.prototype // 兼容性有问题
// 解决方案
var f = function(){}
f.prototype = Human.prototype 
Man.prototype = new f()  

Man.prototype.fight = function(){}

es6: class

class Human {
  constructor(name) {
    this.name = name
  }
  move() {
    console.log('动')
  }
}

class Man extends Human {
  constructor() {
    super()
    this.gender = '男'
  }
  fight() {
    console.log('吃我一拳')
  }
}

在原型上声明一个不是函数的属性:
es5:Human.prototype.race = '人类'
es6:

class Human {
  constructor(name) {
    this.name = name
  }
 race: '人类' // 不支持这样写法,会报语法错误
}
// 变通写法,
class Human {
  constructor(name) {
    this.name = name
  }
  get race(){
    return '人类'
  }
}

总结:
es5的写法稍微复杂一点,但是理解起来简单,看起来更舒服。而es6写法简单,但是更加抽象。
假设把Object和Aaary看作一个类,那么Object和Aaary有什么关系吗?答案是没有。但是Object的prototype和Aaary的prototype有一个关系,那就是JS里面有一个重要的原则,就是所有的类,所有的对象都是从new Object构造出来的。
在JS中继承的实质就是两次的原型链搜索。

相关文章

  • class-继承(es6)

    继承-JS 继承-class class-总结 Class 在语法上更加贴合面向对象的写法Class 实现继承更加...

  • JS中继承的写法

    继承是类和类之间的关系,继承使得子类别具有父类别的属性和方法。 js里常用的如下两种继承方式: 原型链继承(对象间...

  • JS中继承的写法

    继承是面向对象编程很重要的一个方面,让子类继承父类的某些属性和方法,是非常常见的需求。 prototype写法 假...

  • JS 中继承的写法

    下面做一个测试题: 写出一个构造函数 Animal 输入为空 输出为一个新对象,该对象的共有属性为 {行动: fu...

  • JS 中继承的写法

    什么是继承 继承(英语:inheritance)是面向对象软件技术当中的一个概念。如果一个类别B“继承自”另一个类...

  • JS中继承的写法

    继承的两种写法 i.Prototype 写法 ii.Class写法 iii.两种方法的区别 两种方法都能实现继承,...

  • JS 中继承的写法

    es5: es6: class 在原型上声明一个不是函数的属性:es5:Human.prototype.race ...

  • js组件化开发

    如果不了解js的继承的写法,可以先去看看我之前写的js的子类继承父类文章http://www.jianshu.co...

  • onclick JS的错误写法

    如图报了not defined 的错误 我的错误写法 js中 function a(){} 正确写法 js中 a=...

  • JS 的面向对象

    JS 不是一门面向对象的语言,但是很多情况我们需要面向对象。 一、JS 继承的常用写法。 为什么一上来就写常用写法...

网友评论

      本文标题:JS 中继承的写法

      本文链接:https://www.haomeiwen.com/subject/xxmelctx.html