现在的位置: 首页 > 综合 > 正文

Javascript:对象/函数/运算符

2018年01月08日 ⁄ 综合 ⁄ 共 2318字 ⁄ 字号 评论关闭

1.Javascript对象可以直接创建,而无需像java等其它语言那样先定义一个类。
2.由于Javascript是弱类型,因此定义函数时也不需要写参数的类型类型。不需要声明返回值,在函数体中可自由确定是否return一个值。
3.Javascript运算符与java非常类似。

代码整理自w3school:http://www.w3school.com.cn 

效果图:

示例代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />

<title>Javascript 对象与函数</title>

<head type="text/css">
  <style>
    body {background-color:#e0e0e0}
    p.nowrap {display:inline;padding-left:10px}
    p.percent40w {width:40%}

    span.redColor {color:red}
    input.niceStyle {padding:5px}

  </style>
</head>

<body>
  <p>JavaScript 中的所有事物都是对象:字符串、数字、数组、日期,等等。</p>
  <h3>(一)创建一个Javascript对象</h3>
  <script>
    person = new Object();
    person.firstName = "Bill";
    person.lastName = "Gates";
    person.age = 56;

    person.speak = function(){
      alert("I am a person!");
    }

    //访问对象的属性
    document.write(person.firstName+" "+person.lastName+" is "+person.age+" years old.<br/>" );
    document.write("eyescolor:"+person.eyescolor+"<br/>");

    //访问对象的方法
    //person.speak();

    var s = "Hello World"
    document.write("uppercase:"+s.toUpperCase()+"<br/>");
    document.write("length:"+s.length+"<br/>");
    
  </script>

  <h3>(二)带参数的函数</h3>
  <p>点击按钮,调用带参数的函数</p>
  <button onclick="myFunction('Bill Gates','CEO')">点击这里</button>

  <script>
    function myFunction(name,job){
      alert("Welcome " + name + ", the " + job);
    }
  </script>

  <h3>(三)带返回值的函数</h3>
  <input class = "niceStyle" id = "originalText" type="text"/>
  <button type="button" onclick="toUpper()">转为大写</button><br/>
  <p class = "nowrap" id = "upperText"></p>
  <script>
    function toUpper(){
      var x = document.getElementById("originalText").value;
      document.getElementById("upperText").innerHTML = getUpper(x);
    }

    function getUpper(originalText){
      return originalText.toUpperCase()
    }
  </script>

  <h3>(四)JavaScript变量的作用域</h3>
<p class="percent40w">
1.在函数内部声明的变量(使用 var)是局部变量,只能在函数内部访问。可以在不同的函数中使用名称相同的局部变量,因为只有声明过该变量的函数才能识别出该变量。<br/>
2.在函数外声明的变量是全局变量,<span class = "redColor">网页上的所有脚本和函数</span>都能访问它。<br/>
3.局部变量会在函数运行以后被删除,全局变量会在页面关闭后被删除。<br/>
4.如果把值赋给尚未声明的变量,该变量将被自动作为全局变量声明。
</p>

  <h3>(五)JavaScript运算符</h3>
  <p>如果把数字与字符串相加,结果将成为字符串。此规则与java完全相同。</p>
  <script>
    var x = 5+6;
    document.write(x)
    document.write("<br/>")
    x = "5"+"6"
    document.write(x)
    document.write("<br/>")
    x = 5 +"6"
    document.write(x)
    document.write("<br/>")
    x = "5"+6
    document.write(x)
    document.write("<br/>")
    x = 5+6+"6"
    document.write(x)
    document.write("<br/>")
  </script>
  
</body>

</html>

抱歉!评论已关闭.