/**
* 创建对象的方法
* 整理者:Bannings
*/
/**
* 工厂模式
* 缺点:
* 1、构造函数不明,instanceof异常
* 2、不知道是谁的实例
*/
function createPlane(color,speed){
return {
color:color,
speed:speed
};
}
var plane = createPlane("white",280);
/**
* 构造函数
* 优点:
* 1、类与实例之间的关系可以通过instanceof确定
* 2、原型中的构造函数指向正确
* 缺点:
* 1、每个对象拥有独立的相同方法,存在代码冗余
*/
function Plane(color,speed){
this.color = color;
this.speed = speed;
this.fly = function(){
console.log("flying");
}
}
var plane = new Plane("white",280);
console.log(plane instanceof Plane);
/**
* 原型
* 优点:
* 1、所有实例共享原型的属性和方法
* 2、实例的属性可以覆盖原型的属性
* 缺点:
* 1、存在数据共享问题,容易造成数据污染
* 2、无法传递参数
*/
function Plane(){}
Plane.prototype.color = "white";
Plane.prototype.speed = 280;
Plane.prototype.fly = function(){
console.log("flying");
}
var plane = new Plane();
/**
* 构造函数原型组合
* 优点:
* 1、构造函数独享属性,可以传参,没有数据污染问题
* 2、原型独享方法,解决冗余问题
*/
function Plane(color,speed){
this.color = color;
this.speed = speed;
}
Plane.prototype.fly = function(){
console.log("flying");
}
var plane = new Plane("white",280);