【JavaScript】创建对象的四种方式

/**
 * 创建对象的方法
 * 整理者: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);//true

/**
 * 原型
 * 优点:
 * 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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值