JavaScript教程

說明

JavaScript是位於TIOBE前10名的編程語言,主要用於前端。市場佔有率約爲腳本語言老大Python的10%-50%。javascript

本文摘要自Learning JavaScript, 3rd Edition - 2015.pdf
css

源碼地址:https://github.com/EthanRBrown/learning-javascript-3e html


第一個應用

本節基於ES5語法。ECMAScript 5.1 2011發佈。ECMAScript 6 (ES6) 2015發佈。後面的章節基於ES6爲主前端


JavaScript的註釋和c++相似,有//和/* ... */兩種。
HTML的註釋:  <!-- ...  -->
CSS的塊註釋和JavaScript相似。java


HTML、CSS、JavaScript源文件最好分開。node


新建文件:python

main.cssjquery

/* Styles go here. */

main.jsc++

console.log('main.js loaded');

index.htmlgit

<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<html>
    <head>
        <link rel="stylesheet" href="main.css">
    </head>
    <body>
        <h1>第一個實例</h1>
        <p>歡迎來到<i>JavaScript教程</i>.</p>
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
        <script src="main.js"></script>
    </body>
</html>

用瀏覽器打開index.html便可看到頁面。火狐中使用Ctrl-Shift-K (Windows & Linux)或Command-Option-K (Mac)能夠打開控制檯。菜單欄中能夠從工具->Web 開發者中找到。控制檯能夠進行交互式輸入。

使用jQuery能夠替代前面的console。
在<script src="main.js"></script>前面增長:<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>。

修改main.js:

$(document).ready(function() {
    'use strict';
    console.log('main.js loaded');
});

實現與上面相似的效果。

基於HTML5 canvas繪圖:

main.css

/* Styles go here. */
#mainCanvas {
    width: 400px;
    height: 400px;
    border: solid 1px black;
}

main.js

$(document).ready(function() {
    'use strict';
    paper.install(window);
    paper.setup(document.getElementById('mainCanvas'));
    var c = Shape.Circle(200, 200, 50);
    c.fillColor = 'green';
    paper.view.draw();
    console.log('main.js loaded');
});

index.html

<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<html>
    <head>
        <link rel="stylesheet" href="main.css">
    </head>
    <body>        
        <h1>第一個實例</h1>
        <p>歡迎來到<i>JavaScript教程</i>.</p>
        <canvas id="mainCanvas"></canvas>
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.9.24/paper-full.min.js"></script>
        <script src="main.js"></script>
    </body>
</html>

除了Paper.js,KineticJS,Fabric.js 和EaselJS也是常見的canvas圖形庫。

使用循環的實例:

修改main.js

$(document).ready(function() {
    'use strict';
    paper.install(window);
    paper.setup(document.getElementById('mainCanvas'));
    var c;
    for(var x=25; x<400; x+=50) {
        for(var y=25; y<400; y+=50) {
            c = Shape.Circle(x, y, 20);
            c.fillColor = 'green';
    }
}
    c.fillColor = 'green';
    paper.view.draw();
    console.log('main.js loaded');
});


事件處理:

修改main.js

$(document).ready(function() {
	'use strict';
	paper.install(window);
	paper.setup(document.getElementById('mainCanvas'));
	var tool = new Tool();
	tool.onMouseDown = function(event) {
		var c = Shape.Circle(event.point.x, event.point.y, 20);
		c.fillColor = 'green';
	};
	paper.view.draw();
	console.log('main.js loaded');
});

這樣點擊鼠標就會在當前位置畫圓圈。


修改爲經典的hello World!

修改main.js

$(document).ready(function() {
	'use strict';
	paper.install(window);
	paper.setup(document.getElementById('mainCanvas'));
	var c = Shape.Circle(200, 200, 80);
	c.fillColor = 'black';
	var text = new PointText(200, 200);
	text.justification = 'center';
	text.fillColor = 'white';
	text.fontSize = 20;
	text.content = 'hello world';
	paper.view.draw();
	console.log('main.js loaded');
});

JavaScript開發工具


涉及工具:Git、Node、Gulp(或Grunt)構建工具、Babel(翻譯ES6到ES5)、ESLint。

ES6的執行控制檯:http://www.es6fiddle.net/

nodejs不是開發很完整的東東,須要依賴python2.6/7,且不能用centos自帶的包,下面演示如何安裝4.3.1版本,安裝時須要較長時間的編譯。

# curl https://raw.githubusercontent.com/creationix/nvm/v0.13.1/install.sh | bash
# source ~/.bash_profile
# nvm list-remote
# nvm install v4.3.1

目前 172.17.100.19的環境已經OK。


庫安裝:

# npm install underscore

指定版本:npm install underscore@1.8.0

安裝在目錄:node_modules
依賴關係處理:package.json,使用npm init能夠生成。依賴分爲普通和dev。分別用 --save或--saveDev保存,好比:

$ npm install --save underscore

 Babel(https://babeljs.io/)和Traceur(https://github.com/google/traceur-compiler)。
 
 全局安裝:

# npm install babel-cli -g

交互式命令行的使用:

# node
> console.log('hello world');
hello world
undefined
>

babel-nodel命令也能夠實現和node命令相似的效果。

命令行執行:

# vi hello 
#!/usr/bin/env node
console.log('hello world');
# chmod +x hello
# ./hello 
hello world

構建工具:http://gruntjs.com/ http://gulpjs.com/ 這裏基於Gulp。每一個項目的根目錄,執行npm install --save-dev gulp。

# vi gulpfile.js
var gulp = require('gulp');
// Gulp dependencies go here
gulp.task('default', function() {
    // Gulp tasks go here
});
# gulp
[10:32:51] Using gulpfile ~/node_code/gulpfile.js
[10:32:51] Starting 'default'...
[10:32:51] Finished 'default' after 61 μs

Windows下面若是報錯沒有Visual Studio 2010,須要從https://www.visualstudio.com/en-us/visual-studio-homepage-vs.aspx下載安裝。

項目結構:

.git # Git
.gitignore
package.json # npm
node_modules
es6 # Node source
dist
public/ # browser source
    es6/
    dist/
  •     transcompiler

    流行的transcompiler有https://github.com/google/traceur-compiler和https://babeljs.io/。

Babel剛開始轉換ES5爲ES6,後面成爲通用的transcompiler。Babel 6中不包含transformation。

# npm install --save-dev babel-preset-es2015
# vi .babelrc
{ "presets": ["es2015"] }
#  npm install --save-dev gulp-babel
# vi gulpfile.js

const gulp = require('gulp');
const babel = require('gulp-babel');

gulp.task('default', function() {
        // Node source
        gulp.src("es6/**/*.js")
                .pipe(babel())
                .pipe(gulp.dest("dist"));
        // browser source
        gulp.src("public/es6/**/*.js")
                .pipe(babel())
                .pipe(gulp.dest("public/dist"));
});
# vi test.js
'use strict';
// es6 feature: block-scoped "let" declaration
const sentences = [
        { subject: 'JavaScript', verb: 'is', object: 'great' },
        { subject: 'Elephants', verb: 'are', object: 'large' },
];
// es6 feature: object destructuring
function say({ subject, verb, object }) {
        // es6 feature: template strings
        console.log(`${subject} ${verb} ${object}`);
}
// es6 feature: for..of
for(let s of sentences) {
        say(s);
}

執行:

# gulp
# node dist/test.js 
JavaScript is great
Elephants are large
  • lint

安裝

# npm install -g eslint
#  eslint --init
? How would you like to configure ESLint? Answer questions about your style
? Are you using ECMAScript 6 features? Yes
? Are you using ES6 modules? Yes
? Where will your code run? Browser
? Do you use CommonJS? Yes
? Do you use JSX? Yes
? Do you use React Yes
? What style of indentation do you use? Spaces
? What quotes do you use for strings? Double
? What line endings do you use? Unix
? Do you require semicolons? Yes
? What format do you want your config file to be in? JSON
Successfully created .eslintrc.json file in /root/node_code

這樣就生成了.eslintrc.json。

# npm install --save-dev gulp-eslint

修改:gulpfile.js

# vi gulpfile.js 

const gulp = require('gulp');
const babel = require('gulp-babel');
const eslint = require('gulp-eslint');

gulp.task('default', function() {
        // Run ESLint
        gulp.src(["es6/**/*.js", "public/es6/**/*.js"])
                .pipe(eslint())
                .pipe(eslint.format());
        // Node source
        gulp.src("es6/**/*.js")
                .pipe(babel())
                .pipe(gulp.dest("dist"));
        // browser source
        gulp.src("public/es6/**/*.js")
                        .pipe(babel())
                        .pipe(gulp.dest("public/dist"));
});

注意執行下面步驟以前要確認有package.json文件,能夠用npm init生成。

# gulp
[15:09:35] Using gulpfile ~/node_code/gulpfile.js
[15:09:35] Starting 'default'...
[15:09:35] Finished 'default' after 57 ms
[15:09:38] 
es6/test.js
   1:1   error  Strings must use doublequote                            quotes
   4:13  error  Strings must use doublequote                            quotes
   4:33  error  Strings must use doublequote                            quotes
   4:47  error  Strings must use doublequote                            quotes
   5:13  error  Strings must use doublequote                            quotes
   5:32  error  Strings must use doublequote                            quotes
   5:47  error  Strings must use doublequote                            quotes
   5:56  error  Unexpected trailing comma                               comma-dangle
  10:2   error  Expected indentation of 4 space characters but found 0  indent
  10:2   error  Unexpected console statement                            no-console
  14:2   error  Expected indentation of 4 space characters but found 0  indent

public/es6/test.js
   1:1   error  Strings must use doublequote                            quotes
   4:13  error  Strings must use doublequote                            quotes
   4:33  error  Strings must use doublequote                            quotes
   4:47  error  Strings must use doublequote                            quotes
   5:13  error  Strings must use doublequote                            quotes
   5:32  error  Strings must use doublequote                            quotes
   5:47  error  Strings must use doublequote                            quotes
   5:56  error  Unexpected trailing comma                               comma-dangle
  10:2   error  Expected indentation of 4 space characters but found 0  indent
  10:2   error  Unexpected console statement                            no-console
  14:2   error  Expected indentation of 4 space characters but found 0  indent

? 22 problems (22 errors, 0 warnings)

能夠修改.eslintrc開頭的文件定製。更多參考資料:http://eslint.org/


字面量,變量,常量,和數據類型

  • 變量和常量

let currentTempC = 22; // degrees Celsius
// let爲ES6新增,以前只能使用var。

let targetTempC; // equivalent to "let targetTempC = undefined";
let targetTempC, room1 = "conference_room_a", room2 = "lobby";
const ROOM_TEMP_C = 21.5, MAX_TEMP_C = 30;
相關文章
相關標籤/搜索