JavaScript教程

说明

JavaScript是位于TIOBE前10名的编程语言,主要用于前端。市场占有率约为脚本语言老大Python的10%-50%。

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

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


第一个应用

本节基于ES5语法。ECMAScript 5.1 2011发布。ECMAScript 6 (ES6) 2015发布。后面的章节基于ES6为主


JavaScript的注释和c++类似,有//和/* ... */两种。
HTML的注释:  <!-- ...  -->
CSS的块注释和JavaScript类似。


HTML、CSS、JavaScript源文件最好分开。


新建文件:

main.css

/* Styles go here. */

main.js

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>
        <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图形库。

164210_4k8Y_1433482.jpg

使用循环的实例:

修改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');
});

164037_cl7i_1433482.jpg


事件处理:

修改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');
});

165259_f7Lk_1433482.jpg

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;


转载于:https://my.oschina.net/u/1433482/blog/620321

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值