JavaScript创建类的四种方式

类的四种定义方法

1.工厂模式

function Car(name, color, price) {
  var tempcar = new Object; 
  tempcar.name = name; 
  tempcar.color = color; 
  tempcar.price = price; 
  
  tempcar.getCarInfo = function () { 
  	console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); 
  }
  return tempcar;
} 

var mycar = new Car('BMW', 'red', '100000'); 
mycar.getCarInfo(); 
缺点:每次 new 一个对象的时候,都会重新创建一个 getCaeInfo() 函数;

2. 构造函数方式

function Car(name, color, price) { 
    this.name = name; 
    this.color = color; 
    this.price = price; 
    this.getCarInfo = function () {
        console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); 
    } 
} 

var myCar = new Car('桑塔纳', 'green', '123456'); 
myCar.getCarInfo(); 
优点:
  1. 不用创建临时对象;
  2. 不用返回临时对象;
缺点:与‘工厂模式’相同,重复创建函数;

3.原型方式

function Car(name, color, price) { 
    Car.prototype.name = name; 
    Car.prototype.color = color; 
    Car.prototype.price = price; 
    Car.prototype.getCarInfo = function () { 
        console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); 
    } 
} 

var myCar = new Car('兰博基尼', 'red', '10000000000'); 
myCar.getCarInfo(); 
优点:
  1. 解决了重复创建函数的问题;
  2. 可以使用 instanceof 检验类型 myCar instanceof Car // true
缺点: 多个实例创建的相同属性指向同一块内存;
例子:
Car.prototype.drivers = ['Tim', 'Jone']; 
myCar.drivers.push('mike'); 
console.log(myCar.drivers); // ['Tim', 'Jone', 'mike'] 

4.动态原型方式(推荐)

function Car(name, color, price, drivers) { 
    this.name = name; 
    this.color = color; 
    this.price = price; 
    this.drivers = drivers; 
}

Car.prototype.getCarInfo = function () { 
    console.log(`name: ${this.name},color: ${this.color},price: ${this.price}`); 
} 

var myCar = new Car('兰博基尼', 'red', '10000000000', ['qaz', 'wsx']); 
myCar.drivers.push('mi'); 
console.log(myCar.drivers); // ["qaz", "wsx", "mi"] 
var myCar1 = new Car('兰博基尼1', 'red1', '100000000001', ['qaz1', 'wsx1']); 
myCar1.drivers.push('mi1'); 
console.log(myCar1.drivers); // ["qaz1", "wsx1", "mi1"] 
思想:
类的属性 要随实例对象动态改变; => 动态
类的方法 要随原型保持不变;=> 原型
上一篇:JavaScript 中 in 运算符的用法详解


下一篇:ORACLE JAVA JDK/JRE 获取/下载地址(含1.6/1.7/1.8所有历史版本)