第五课--对象

18 阅读1分钟

JavaScript 中的所有事物都是对象:字符串、数值、数组、函数...此外,JavaScript 允许自定义对象。
a.访问对象的属性
objectName.propertyName
b.访问对象的方法
objectName.methodName()
c.创建 JavaScript 对象
通过 JavaScript,您能够定义并创建自己的对象。
创建新对象有两种不同的方法:
定义并创建对象的实例
使用函数来定义对象,然后创建新的对象实例.
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";


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;
}
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        function obj(a,b,c){
            this.a = a;
            this.b = b;
            this.c = c;
            this.sum = sum;
            function sum(a,b,c){
                    return a+b+c;
            }
        }   
        var my_obj = new obj(1,2,3)
        console.log(my_obj.a)
        console.log(my_obj.b)
        console.log(my_obj.c)
        console.log(my_obj.sum(3,4,5))
    </script>
</body>
</html>