Try   HackMD

NTUOSC JavaScript

20160311 Elantris
Note: https://hackmd.io/s/N1ERJm5Ux

tags: 2016 ntuosc javascript

Setup

Browser

  • Apple Safari
  • Google Chrome
  • Mozilla Firefox

Editor

  • Notepad++
  • Github Atom
  • Sublime Text
  • Vim
  • Emacs

Node.js

https://nodejs.org

Create a folder and install node modules

$ npm install -g browserify
$ mkdir myProject
$ cd myProject
$ npm install react react-dom babelify babel-preset-react moment

Packages

  • react
  • react-dom
  • babelify
  • babel-preset-react
  • moment

Basic

Variable

  • Undefined
  • Boolean
  • Number
  • String
  • Array
  • Object
  • Function
// Undefined
var bool = true; // Boolean
var num = 5; // Number
var str = 'this is a "string"'; // String
var ary = [1, 3, 'str', ['another', 'array'], 312]; // Array
var obj = { // Object
    a: 'Apple',
    b: 'Banana',
    c: 1000,
    d: ['an', 'array'],
    o: { r: 'recursive' }
};

Function

Define Function

function add(a, b) { // parameter
    var sum; // local variable
    sum = a + b; /* do something ... */
    return sum; // return or not
}

var multiply = function(a, b) { // parameter
    var p; // local variable
    p = a * b; /* do something ... */
    return p; // return or not
}

Call Function

add(5, 10); // return 15, but not print
console.log(multiply(5, 10)); // print 50

Pass Parameter

var result = add(multiply(4, 6), add(5, 10)); // 24 + 15

console.log(result); // 39

Object

Everything in JavaScript is Object.

  • Object
    • Boolean
    • Number
    • String
    • Function
    • (Array)

All Types of variables extend Object

Use typeof to check the type of object

console.log(typeof true); // 'boolean'
console.log(typeof 345); // 'number'
console.log(typeof 'feizhai'); // 'string'
console.log(typeof setTimeout); // 'function'
console.log(typeof [1, 'a', 3, 'c']); // 'object'
console.log(typeof { a: 'apple' }); // 'object'

Define an object

var feizhai = {
    name: 'Victor',
    age: 19,
    height: 170,
    weight: 'very fat',
    languages: ['C/C++', 'Python', 'PHP', 'HTML/CSS', 'JavaScript'],
    coding: function(t) {
        console.log('The ' + this.weight + ' ' + this.name + ' starts coding!');
        console.log('He is using "%s" to finish the project.', this.languages[t]);
    },
    sleep: function() {
        console.log('The ' + this.weight + ' ' + this.name + ' is sleeping!');
        console.log('Oh, no! He will not wake up until the end of the class.');
    },
    gotoSchool: function() {
        this.coding(2);
        this.sleep();
    }
};

Get values of objects

feizhai.name // 'Victor'
feizhai.height // 170
feizhai['weight'] // 'very fat'
feizhai.language[2] // 'Python'

feizhai.gotoSchool();
// The very fat Victor starts coding!
// He is using "PHP" to finish the project.
// The very fat Victor is sleeping!
// Oh, no! He will not wake up until the end of the class.

Iterate an object

var ary = ['alpha', 'bravo', 'charlie'];
for (var i in ary) console.log(i + ': ' + ary[i]);

var obj = {
    'a': 'alpha',
    'b': 'bravo',
    'c': 'charlie'
};
for (var i in obj) console.log(i + ': ' + obj[i]);

output

0: alpha
1: bravo
2: charlie
a: alpha
b: bravo
c: charlie

Pass a Function object as parameters

function getRandomInt() {
    return Math.floor(Math.random() * 100);
}

function getRandomChar() {
    var c = 'qwertyuiopasdfghjklzxcvbnm';
    return c[getRandomInt(0, c.length)];
}

function display(words, rand) {
    console.log(words + ' ' + rand());
}

display('Today\'s lucky number is', getRandomInt);
display('I want a random alphabet:', getRandomChar);

Anonymous Function

function display(words, rand) {
    console.log(words + ' ' + rand());
}

display('Let\'s have a function without name:', function() {
    var output = 'Hi, I am an anonymous function!';
    return output;
});

Define an anonymous function and call immediately

(function() {
    console.log('I am an anonymous function, too.');
    console.log('I will do something immediately.');
})();

JSON

JavaScript Object Notation

  • Boolean true or false
  • Number 123
  • String ""
  • Array []
  • Object {}
{
    "name": "Victor",
    "age": 19,
    "single": true,
    "language": ["C/C++", "Python", "PHP", "HTML/CSS", "JavaScript"],
    "race": "Feizhai",
    "course": {
        "Open System Software": {
            "credit": 3,
            "time": ["TUE 2", "TUE 3", "TUE 4"]
        },
        "Algorithm": {
            "credit": 3,
            "time": ["TUE 7", "TUE 8", "TUE 9"]
        },
        "Introduction to Information Management": {
            "credit": 3,
            "time": ["WED 2", "WED 3", "WED 4"]
        },
        "Theory of Computing": {
            "credit": 3,
            "time": ["WED 7", "WED 8", "WED 9"]
        },
        "Operations Research": {
            "credit": 3,
            "time": ["THR 2", "THR 3", "THR 4"]
        }
    }
}

Node

https://nodejs.org

Usage

$ node -v
v5.8.0
$ node myScript.js

Node Package Manager

https://www.npmjs.com

Usage

$ npm -v
3.8.1
$ npm install -g browserify

JS Module

JavaScript module in two formats

AMD

// export module
define(['jquery'] , function ($) {
    return function () {};
});
// import module
require(['jquery'], function($) {
    $('body').html('<h1>Hello world!</h1>');
});

Implement: Require.js

CommonJS

// export module
module.exports = $;
// import module
var $ = require('jquery');

Implement: Node.js

Example of CommonJS

getRandomInt.js

function getRandomInt() {
    return Math.floor(Math.random() * 100);
}

module.exports = getRandomInt;

operation.js

function add(a, b) { return a + b; }

var multiply = function(a, b) { return a * b; }

module.exports = {
    add: add,
    multiply: multiply
};

myScript.js

var getRandomInt = require('./getRandomInt.js');
var operation = require('./operation.js');

var a = getRandomInt();
var b = getRandomInt();

var sum = operation.add(a, b);
var product = operation.multiply(a, b);

console.log(a + ' ' + b);
console.log('a + b = ' + sum);
console.log('a * b = ' + product);

React

Official Site

// main.js
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('example')
);

File Type: JSX (JSX in Depth)

JavaScript with XML

Use npm

Install Packages

$ npm install react react-dom babelify babel-preset-react moment

Bundle Main File

$ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js

Component

Docs

Component Specifications

  • getInitialState: function
  • getDefaultProps: function
  • propTypes: object
  • mixins: array
  • statics: object
  • render: function

Lifecycle Methods

  • Mount
    • componentWillMount
    • componentDidMount
  • Update
    • componentWillReceiveProps
    • shouldComponentUpdate
    • componentWillUpdate
    • componentDidUpdate
  • Unmount
    • componentWillUnmount

Example

var React = require('react');
var ReactDOM = require('react-dom');
var moment = require('moment');

var timeNow = {
    getInitialState: function() {
        return {
            today: moment(),
            index: 0,
            format: ['', 'MMMM Do YYYY, h:mm:ss a', 'dddd', "MMM Do YY", 'YYYY [escaped] YYYY'],
            show: ''
        };
    },
    componentDidMount: function() {
        this.setState({ len: this.state.format.length, show: this.state.today.format() });
    },
    handleHover: function() {
        var index = (this.state.index + 1) % this.state.len;
        var show = this.state.today.format(this.state.format[index]);
        this.setState({ index: index, show: show });
    },
    render: function() {
        return (<div onMouseOver={this.handleHover}>Today is {this.state.show}</div>);
    }
};

var TimeNow = React.createClass(timeNow);

ReactDOM.render(<TimeNow />, document.getElementById('time'));

Class

var TimeNow = React.createClass(timeNow);

ReactDOM.render(<TimeNow />, document.getElementById('time'));