当前位置: 移动技术网 > IT编程>网页制作>HTML > Object-创建对象常用的六种方法

Object-创建对象常用的六种方法

2020年10月29日  | 移动技术网IT编程  | 我要评论
Object-创建对象常用的六种方法话不多说,上代码!!!<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>创建对象的常用的6种方法</title></head

Object-创建对象常用的六种方法

话不多说,上代码!!!

1.对象实例化

        //1对象实例化-(没对象?new一个不就完了^v^,>o<)
        var a = new Object();

2.字面量声明法

        //2字面量声明
        var b = {
            name:'张三';
        }

3.工厂模式

        //3 工厂模式
        function aa(name,age){
            //1) 原材料
            var bb = new Object();
            bb.name = name;
            bb.age = age;
            //2)加工
            bb.create = function(){
               console.log('我的名字是'+ bb.name+"年龄"+bb.age);
            }
            // 3)完工把对象返回出去
            return bb;
        }
        var zhangsan = aa('张三',18);
        var lisi = aa('李四',20);
        // console.log(zhangsan);
        // console.log(lisi);
        // console.log(zhangsan.create());

4.构造函数

        //4 构造函数
        function bb(name,age){
            this.name = name;
            this.age = age;
            this.create = function(){
               console.log('我的名字是'+ this.name+"年龄"+this.age);
            }
        }
        var ccc = new bb('赵六',21);
        var bbb = new bb('赵六',21);
        // console.log(ccc.create == bbb.create);
        //构造函数和工厂模式区别
        // 工厂模式里面要 new 一个对象 ,还需要return 这个对象

5.原型对象

        //5 原型对象
       function ooo(name,age){
           ooo.prototype.name = name;
        //    this.age = age;
       }
       var pp = new ooo('张三',19);
       var ll = new ooo('李四',20);
       console.log(pp.name == ll.name);  // true
       console.log(pp.age == ll.age);
       console.log('------');
       console.log(pp);
       console.log(ll);
       console.log('------');

6.混合模式(原型加构造函数)

        //6 混合模式(原型加构造函数 )
        function bb(name,age){
            this.name = name;
            this.age = age;
            this.create = function(){
               console.log('我的名字是'+ this.name+"年龄"+this.age);
            }
        }
        bb.prototype.run=function(){
            console.log(this.name+"会跑");
        }
        var eee = new bb();
        var ttt = new bb();
        // console.log(eee.run == ttt.run);
        console.log(eee.__proto__);
        console.log(bb.prototype);
        console.log(bb.prototype == eee.__proto__);
        eee.__proto__.abc=function(){
            alert('abc');
        }
        console.log(bb.prototype);
        var nnn = new bb();
        console.log(nnn);

小结:
// _proto_ 这是对象里面的原型添加方法
// prototype 这是构造函数里面的原型添加方法

本文地址:https://blog.csdn.net/yuan_xiaoxin/article/details/109353290

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网