码迷,mamicode.com
首页 > 其他好文 > 详细

es6 class extends

时间:2019-06-01 09:47:20      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:end   后端   xtend   关系   初学者   一点   hash   this   基础   

Class和普通构造函数有何区别
 
JS构造函数
function MathHandle(x, y){
  this.x = x;
  this.y = y;
}
MathHandle.prototype.add = function () {
  return this.x + this.y;
}
var m = new MathHandle(1,2);
console.log(m.add());

第一块是构造函数,第二块是构造函数的一个拓展,下面是将构造函数实例化,最后调用add方法,因为这个原型扩展之后,每个实例都会有这个方法。

typeof MathHandle // true
MathHandle.prototype.constructor === MathHandle // true
每个构造函数都有一个prototype,显示原型,prototype默认都有constructor属性,这个属性指的就是这个构造函数本身
m.__proto__ === MathHandle.prototype // true
所有实例都有一个隐式原型,这个隐式原型等于构造函数的显示原型。这个是写js构造函数的必备基础

 

Class基础语法
class MathHandle{
  constructor(x,y){
    this.x = x;
    this.y = y;
  }
  add() {
    return this.x + this.y;
  }
}
const m = new MathHandle(1,2);
console.log(m.add());

constructor是一个构造器,每个class都有一个constructor。es6中,用class来专门做构造函数的语法其实是有点模拟java,c#的语法,让初学者或后台熟悉一点。下面的add相当于在原型中定义add方法。这里定义class的方法跟js构造函数相比,更加简单。constructor在new的时候立马会执行。

 

typeof MathHandle // "function"

本质上是个函数,明明没有写function,所以js中本身是没有class的,所以这个class的本质是函数

MathHandle === MathHandle.prototype.constructor // true

跟js构造函数本质是一样的,这是语法糖。

m.__proto__ === MathHandle.prototype // true

m的实例也是等雨构造函数的显示原型

js的原理知识,能对上class的原理知识,一摸一样

 

语法糖
这两种写法本质是一样的,这种语法糖形式,和实际原理看起来不一样了,形式上模拟java c#,这样却失去了他的本性。所以不继续学习就不知道本质是什么东西。class可以提高初学者,后端的学习成本。但是前端需要知道本质

 

继承

 

// 动物
function Animal() {
  this.eat = function(){
    console.log(‘animal eat‘)
  }
}
//
function Dog() {
  this.bark = function () {
    console.log(‘dog bark‘);
  }
}
// 绑定原型,实现继承
Dog.prototype = new Animal();
// 哈士奇
var hashiqi = new Dog();

继承就是抽象到具象的过程,从高级到低级的一个关系,首先有一个animal,动物是抽象的,然后是狗,再往下是哈士奇,哈士奇是一种狗。每个animal都有eat,动物都要吃。dog有个bark,叫。这两个构造函数比较简单,就是两个函数,里面有个属性。重点是我们把Dog的显示原型赋值成new Animal()。new Animal是出实话一个animal的实例。这样就实现了继承。再去new Dog(),肯定有bark的方法,执行了赋值之后,也有了eat的方法。

hashiqi.bark();
hashiqi.eat();
这是js的继承



class Animal{
  constructor(name){
    this.name = name;
  }
  eat() {
    console.log(this.name + ‘ eat‘)
  }
}
class Dog extends Animal {
  constructor(name) {
    super(name);
    this.name = name;
  }
  bark() {
    console.log(this.name + ‘ bark‘);
  }
}
const dog = new Dog(‘哈士奇‘);
dog.bark();
dog.eat();

Dog.prototype = new Animal() 相当于 class Dog extends Animal。后面跟java非常相似。这样已经继承了原型方法,不用再写.prototype这种。。super(name),也就是说在执行Dog的构造器的时候,我先把Animal的构造器执行一遍。Animal这个构造函数对应 class Animal。Dog这个构造函数,对应 class Dog。

 

es6 class extends

标签:end   后端   xtend   关系   初学者   一点   hash   this   基础   

原文地址:https://www.cnblogs.com/wzndkj/p/10958451.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!