Day1-JS-JavaScript对象与函数

JavaScript 对象

-------------JavaScript 对象是拥有属性和方法的数据

一、对象的简单使用  

<body>
    <p id="demo"></p>
    <script>
        var person={firstName:"hzy",lastName:"j",age:50,eyeColor:"blue"};
        document.getElementById("demo").innerHTML=
        person.firstName+" 现在"+person.age+"";
    </script>
</body>

二、对象方法

直接在对象里面建立 fullname:function(){}

之后直接调用通过person.fullname()即可

<body>
    <p id="demo"></p>
    <script>
        var person={
            firstName:"hzy",
            lastName:"hzy",
            age:19,
            fullname:function(){
                return this.firstName+" "+this.lastName;
            }
        }
        document.getElementById("demo").innerHTML=person.fullname();
    </script>
</body>

知识点:如果不加括号( 

person.fullname;
           )
直接输出的话(也就直接把这个函数给打印出来了)
不加括号输出函数表达式:function() { return this.firstName + " " + this.lastName; }
三、JavaScript函数
1、简单实例(通过一个按钮激活函数)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function myFunction()
        {
            alert("hzy");
        }
    </script>
</head>
<body>
   <button onclick="myFunction()">点我咯</button>

</body>
</html>
View Code

 2、带参数的函数

知识点:在onclock中给函数传入值的时候要用 单引号 才行

<body>
    <button onclick="myFunction('hzy','pig')">点我咯</button>
    <script>
        function myFunction(name,job){
            alert("Welcome "+name+", the "+job);
        }
    </script>
</body>

 3、带返回值的函数

<body>
    <p id="demo"></p>
    <script>
        function myFunction(a,b){
                return a*b;
        }
        document.getElementById("demo").innerHTML=myFunction(1,2);
    </script>
</body>
 

  

原文地址:https://www.cnblogs.com/SCAU-gogocj/p/13093178.html