对象的7种创建方式

body>
    <script>
        //1、用new object方式
        const obj1 = new Object()
        obj1.name = 'zhuzhu'
        obj1.age = 17
        console.log(obj1);//{name: 'zhuzhu', age: 17}

        //2、用字面量的方式
        const obj2 = {
            name: 'xinxin',
            age: 18
        }
        console.log(obj2);//{name: 'xnxin', age: 18}

        //3、factory模式
        function Student(name, age) {
            const obj3 = {
                name: name,
                age: age
            }
            return obj3
        }
        const aa = new Student('aa', 18)
        console.log(aa);//{name: 'aa', age: 18}

        //4、构造函数

        //语法格式;
        // function 构造函数名(){
        //     this.属性=值;
        //     this.方法=function(){}
        // }
        // new 构造函数名

        function Student(name, age) {
            this.name = name,
                this.age = age,
                this.playGame = function (game) {
                    console.log(game);//Student {name: 'aa', age: 18, playGame: ƒ}
                }
        }
        var yy = new Student('yy', 18)
        console.log(yy.name);//yy
        console.log(yy.age);//18
        yy.playgame('王者')//王者

        //5、原型方式
        function Student1() {

        }
        Student1.prototype.name = 'zz'
        Student1.prototype.age = 18;
        Student1.prototype.sayHi = function (hi) {
            console.log(hi);
        }
        const zz = new Student1('zz', 18)
        zz.sayHi('你好')//你好

        //6、构造函数+原型的方式
        function Student3(name, age) {
            this.name = name;
            this.age = age
        }
        Student3.prototype.help = function (hp) {
            console.log(hp);
        }
        const AA = new Student3('AA', 18)
        AA.help('今天教会了同学一道数学题')//今天教会了同学一道数学题

        //7、类方式
        class Student6 {
            constructor(name, age) {
                this.name = name,
                    this.age = age
            }
            build(family) {
                console.log(family);
            }
        }
        const lp = new Student6('牛皮', 18)
        lp.build('建设美好家园')//建设美好家园
    </script>
</body>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值