js对象定义的最常用的三种方法

定义对象:属性和方法的结合体(变量和函数的结合体)
1.(***)var obj = {}

2.var obj = new Object();

3.使用function定义对象

具体例子分别为:

 1 // 1.定义obj的对象
 2     // obj:对象名
 3     var obj = {
 4         // height,weight,sex称为对象的属性
 5         height: 170,        // 使用,分隔属性和方法
 6         weight: 90,
 7         sex: '大美女',
 8 
 9         // say():称为对象的方法
10         say: function(){
11             alert('付帅帅,你有长帅了');
12         },
13         eat: function(){
14             alert('吃饭');
15         }
16     }
17 
18     // 获取对象的属性(对象名.属性名)
19     console.log(obj.weight);
20     // 调用对象的方法(对象名.方法名())
21     // obj.say();
 1 // 2.定义了一个空对象
 2     var o1 = new Object();
 3     // 给对象赋值属性
 4     o1.height = '150cm';
 5     o1.color = 'silver';
 6     o1.fire = function(){
 7         alert('砍了它,当柴火烧');
 8     }
 9 
10     // 调用
11     console.log(o1.height);
12     // o1.fire();
// 3.使用函数来定义对象
    function demo(){
        // this代表的是当前的对象
        this.memory = '16G';
        this.hard = '1T';

        this.ys = function(){
            alert('此刻电脑正在进行高负荷的运算');
        }
    }

    // 调用(实例化demo()函数)
    var d = new demo();

    console.log(d.memory);
    d.ys();
原文地址:https://www.cnblogs.com/jkr666666/p/6696963.html