天天看点

JavaScript对象_创建对象

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/55655478

创建对象

1,直接用Object()创建对象,再向对象中添加属性

person=new Object();
person.firstname="Bill";
person.lastname="Gates";           

2,使用花括号创建

person = {firstname:”bill”,lastname:”gates”}

3,使用函数构造对象

var tom = new student();

<html>
    <body>
    <script>
        //使用函数构造对象
        function student(name,num,grade){
            this.name = name;
            this.num = num ;
            this.grade = grade;
        }

        var tom = new student("tom",12345,100);
        alert(tom.name);
    </script>

    </body>
</html>
           

1,属性名可以用引号括起来,单引号或双引号

2,新建对象时new Object()中的new可以省略

在对象中创建方法。

<html>
//在对象中创建方法
    <body>

    <script>
    //对象构造器
        function person(firstname,lastname,age,eyecolor){
            this.firstname = firstname;
            this.lastname = lastname;
            this.age = age;
            this.eyecolor = eyecolor;

            this.changeName = changeName;

            //函数位置不固定,但是要在使用之前创建
            function changeName(name){
                this.lastname = name;
            }
        }

        var ss = new person("first","last",40,"black");
        ss.changeName("new name");
        alert(ss.lastname);
    </script>

    </body>
</html>           

使用匿名函数:

var jerry = {
        name: 'jerry',
        age: 10,
        run:function(){
            return '123';
        }
    }           

遍历一个对象中的所有属性。下面的代码运行结果是:BillGates30

<html>
    <body>
    <script>
        var person = {fname:"Bill",lname:"Gates",age:30};
        for(var s in person){
            document.write(person[s]);
        }
    </script>

    </body>
</html>           

在对象中添加函数时,以下面的run方法为例:

function run(){
            alert("2333");
            return "@@@";
        }           

如果赋值时不加括号,使用时也不加括号就类似于一个字符串

赋值:this.myrun = run;

调用:tom.myrun; —>不会执行

调用:alert(tom.mytom);—>弹出函数的源代码

如果赋值时加了括号,在调用时可加可不加:

赋值:this.myrun = run();

调用:tom.myrun; or tom.myrun();

不可以这样赋值:

this.myrun() = run();

删除变量成员

delete jerry.name;

继续阅读