Web前端之路让前端飞

JavaScript中的复用和抽象

2020-05-13  本文已影响0人  ZoranLee

复用、抽象

image.png

JavaScript实现方式

ES6之后

原型复用示例

//创建“猫”对象
var cat = {
    say(){
        console.log("meow~");
    },
    jump(){
        console.log("jump");
    }
}
//根据猫,修改创建了虎
var tiger = Object.create(cat,  {
    say:{
        writable:true,
        configurable:true,
        enumerable:true,
        value:function(){
            console.log("roar!");
        }
    }
})


var anotherCat = Object.create(cat);

anotherCat.say();

var anotherTiger = Object.create(tiger);

anotherTiger.say();

类与原型

image.png

之前版本new+function 来模拟对象

模拟类创建对象

function c1(){
//直接在构造器中修改this,给this添加属性
    this.p1 = 1;
    this.p2 = function(){
        console.log(this.p1);
    }
} 
var o1 = new c1;
o1.p2();

function c2(){
}
//修改构造器的prototype属性指向的对象
c2.prototype.p1 = 1;
c2.prototype.p2 = function(){
    console.log(this.p1);
}

var o2 = new c2;
o2.p2();

ES6 中的类

class Rectangle {
constructor(height, width){
this.height = height;
    this.width = width;
}
 // Getter
  get area() {
    return this.calcArea();
  }
// Method
  calcArea() {
    return this.height * this.width;
  }
}
class Animal { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name); // call the super class constructor and pass in the name parameter
  }

  speak() {
    console.log(this.name + ' barks.');
  }
}

let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.

使用类的思想来设计代码时,应该尽量使用class来声明类

上一篇下一篇

猜你喜欢

热点阅读