JavaScript基础

2017-03-31  本文已影响0人  peterzen

使用JS的形式

内嵌JS

<head>
    <script type="text/javascript">
        document.write("开启JS之旅");
    </script>
</head>

引用外部JS

<head>
    <script src="script.js"></script>
</head>

注释

注释格式同c语言,有单行“//”和多行"/* */"两种

变量

var mychar = "javascript";

数据类型

基本数据类型(值类型)

引用类型

对于引用类型,可以动态添加属性和方法,也可以改变和删除其属性和方法。

var person = new Object();
person.name = "nicholas";
alert( person.name );

传递参数

所有函数的参数都是按照值传递的。

function setName( obj ) {
    obj.name = "nicholas";
}
var person = new Object();
setName( person );
alert( person );    // "Nicholas"

// another sample
function setName( obj ) {
    obj.name = "Nicholas";
    obj = new Object();
    obj.name = "Greg";
}
var person = new Object();
setName( person );
alert( person.name );       // "Nicholas"

检测类型

typeof
var s = "Nicholas";
var b = true;
var i = 22;
var u;
var n = null;
var o = new Object();

alert( typeof s );      // string
alert( typeof i );      // number
alert( typeof b );      // boolean
alert( typeof u );      // undefined
alert( typeof n );      // object
alert( typeof o );      // object
instanceof
alert( person instanceof Objecct );

作用域

有全局和局部变量,没有块级作用域

引用类型

对象属性的访问

// 如下两种访问方式相同
var name = person[name];
var name = person.name;
// 如果属性名中包含会导致语法错误的字符,或者包含关键字,则使用方括号访问方式
person["first name"] = "peter";

除非必须使用方括号的方式,通常建议使用点的方式进行访问。

继承

使用prototype实现继承

function Animal() {
    Animal.prototype.species = "动物";
}

function extend( Child, Parent ) {
    var F = function() {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
}

// usage
extend( Cat, Animal );
var cat1 = new Cat( "大毛", "黄色" );
alert( cat1.species );

函数表达式

闭包

闭包是指有权访问另一个函数作用域中的变量的函数。
创建闭包的常见方式,就是在一个函数内部创建另一个函数。

Array

var showTime = [ "12:30", "2:34", "5:00" ];
var arr = new Array();

// Array operation
var colors = new Array();
var count = colors.push( "red", "green" );
colors.pop();   // LIFO
colors.shift(); // FIFO

Date类型

var someDate = new Date( Date.parse( "May 25, 2004" ) );
// 以下的方式也会在后台调用Date.parse
var someDate = new Date( "May 25, 2004" );
// 2005-05-05 17:55:55
var day = new Date( 2005, 4, 5, 17, 55, 55 );
date.now();

从一个函数返回另一个函数

function createCompareFunction( propertyName ) {
    return function( obj1, obj2 ) {
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        
        if( value1 < value2 ) {
            return -1;
        } else if( value1 > value2 ) {
            return 1;
        } else {
            return 0;
        }
    }
}

var data = [{name: "Zark", age: 18}, {name: "Richo", age: 29}];
data.sort( createCompareFunction( "name" ) );
data.sort( createCompareFunction( "age" ) );

函数内部属性

// 使用arguments.callee来做递归
function factorial( num ) {
    if( num <= 1 ) {
        return 1;
    } else {
        return num * arguments.callee( num - 1 );
    }
}

// this
window.color = "red";
var o = { color: "blue" };

function sayColor() {
    alert( this.color );
}

sayColor();         // "red"

o.sayColor = sayColor;
o.sayColor();       // "blue"

output

document.write( "I love JavaScript!" );

条件语句

if

var myage = 80;
if( score >= 60 ) {
    document.write( "fantasic" );
} else {
    document.write( "you need study harder" );
}

switch

switch( chooseCase ) {
case "A":
    openCase( "A" );
    break;
case "B":
    ...
    break;
}

循环

for

for( var x = 0; x < 37; x++ ) {
    takeStep();
}

while

while( !rockVisible )
    takeStep();

button

button click

<head>
    <script type="text/javascript">
        function rec() {
            var mychar = "I Love JavaScript";
            alert( mychar );
        }
    </script>
</head>
<body>
    <input name="button" type="button" onClick="rec()" value="Click Me" />
</body>

function

function context() {
    alert( "function called" );
}

functions

Timer

// 单次定时器,单位是ms
setTimeOut( "alert('Wake up!');", 6000 );

// 间隔定时器
var timerId = setInterval( "alert('Wake up!' );", 6000 );
// 清除定时器
clearInterval( timerId );

Interval

var myInterval = setInterval( myFunc, 100000 );
...
clearInterval( myInterval );

根据屏幕size调整图像

function resize() {
    document.getElementById( "rockImg" ).style.height = ( document.body.clientHeight - 100 ) * 0.9;
}

判断浏览器是否支援cookie

var cookieSupport = navigator.cookieEnable;

对话框

alert

confirm

var ret = confirm( "are you male or female?" );
if( ret == true ) {
    document.write( "you are male!" );
}

prompt

var score = prompt( "what is your score?", "60" );
if( score >=90 ) {
    document.write( "fantasic" );
}

open new window

// window.open( [URL], [window name], [param] );
window.open( "http://www.imooc.com", "_blank", width=600, height=400, top=100, left=0 );

close window

window.close(); //close current window
//close specified window
var mywin = window.open( "http://baidu.com" );
mywin.close();

DOM

通过ID获取元素

<body>
<div id="con">JavaScript</div>
<script type="text/javascript">
    var mychar = document.getElementById( "con" );
    document.write( "result: " + mychar );
</script>
</body>

innerHTML属性

<body>
    <h2 id="con">javascript</h2>
    <script type="text/script">
        var mychar = document.getElementById( "con" );
        mychar.innerHTML = "Hello, World!";
    </script>
</body>

改变HTML样式

var mychar = document.getElementById( "con" );
mychar.style.color = 'red';
mychar.style.backgroundColor = '#ccc';
mychar.style.width = '300px';

更改控制类名

<head>
    <style type="text/css">
        .one {
            width: 200px;
            background-color: #ccc;
        }
        .two {
            font-size: 18px;
            color: #F00;
        }  
    </style>
</head>
<body>
    <p id="con" class="one">JavaScript</p>
    <input type="button" value="Click Me" onclick="modifyClass()" />
    <script type="text/javascript" >
        var mychar = document.getElementById( "con" );
        function modifyClass() {
            mychar.className = "two";
        }   
    </script>
</body>

表单脚本

HTMLFormElement

提交表单

<!-- 通用提交按钮 -->
<input type="submit" value="Submit Form">
<!-- 自定义提交按钮 -->
<button type="submit">Submit Form</button>
<!-- 图像按钮 -->
<input type="image" src="graphic.gif">
上一篇下一篇

猜你喜欢

热点阅读