代码-JS之定义对象的方式

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<script>

    //1.构造函数方式
    function A() {
        this.name = '时分秒';
        this.age = 22;
        this.info = ['55kg', '180cm'];
        this.skill = function () {
            console.log('我能吃');
        }
    }
    //实例化对象,每实例化一次,会占用一个内存空间
    var a = new A();
    var a1 = new A();
    var a2 = new A();
    //缺点:这种方式定义的对象会占用很多内存,因为每个对象创建单独的空间,存储各自的内容

    //2.原型对象方式
    function B() {
        B.prototype.name = '犬夜叉';
        B.prototype.age = 25;
        B.prototype.info = ['66kg', '185cm'];
        B.prototype.skill = function () {
            console.log('我能打');
        }
    }
    //实例化对象,每次实例都将指向原型对象
    var b = new B();
    var b1 = new B();
    var b2 = new B();
    b.info.push('strong');
    console.log(b1.info);   //结果:(3) ["66kg", "185cm", "strong"]
    //缺点:当改变一个对象的引用类型的属性后,其他对象也发生了变化

    //3.混合方式定义
    function C(){
        this.name = '奈落';
        this.age = '200';
        this.info = ['190cm', '60kg']
    }
    C.prototype.skill = function () {
        console.log('我会骗');
    }
    var c = new C();
    C.prototype.skill();
    //混合是指构造函数方式和原型对象方式混合,将属性放到构造函数内部,将成员方法放到原型对象中。

    //4.动态混合方式
    function D() {
        this.name = '桔梗';
        this.age = 22;
        this.info = ['178cm', '50kg']
        if(!D.prototype.skill){
            D.prototype.skill = function () {
                console.log('我爱阿狸');
            }
        }
    }
    var d = new D();
    d.skill();
    //有些类似PHP中的单例模式

</script>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值