9-73 Requirements

  • Greeter
  • input : firstname lastname and optional language
  • output : formal and informal greeting sentence
  • language support English and Spanish
  • reusable
  • just G$() to call (no ‘new’)
  • support jQuery(give selector, add greeting sentence to the selected element)
Continue reading

8-70 8-71 jQuert Part1、2

jQuery Structure
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

// IIFE

(function(global, factory){
...

// invoked factory
return factory(global);
}(window, function(window, noglobal){
version = "1.11.2",

// Define a local copy of jQuery
jQuery = function( selector, context ) {

return new jQuery.fn.init( selector, context );
},
.
.
.

// nickname for prototype
jQuery.fn = jQuery.prototype ={
...
};

//Merge the contents of two or more objects together into the first object.
jQuery.extend = jQuery.fn.extend = function() {
...

// jQurry habe makeArray property which is a function
makeArray: function( arr, results ) {
var ret = results || [];

if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}

return ret;
}

...
}

//use extend to add properties on jQuery
jQuery.extend({...});

// Sizzle CSS Selector Engine
// another IIFE inside IIFE
var Sizzle =(function (window){});

// real init funciton
init = jQuery.fn.init = function( selector, context ) {
...


// this point to the empty object, created by calling new function
// makeArray still return this
return jQuery.makeArray( selector, this );
}

// set up the new object's prototype ctreated by new
init.prototype = jQuery.fn;

//window from line 8
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,

// Map over the $ in case of overwrite
_$ = window.$;

// Expose jQuery and $ identifiers
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}

return jQuery;

}));

8-73 jQuert Part3

bigword alert : Method chaining

  • calling one method after another, and each method affects the parent object.
  • obj.method1().method2()

how to implements method chain

  • functions return this
jquery addClass function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;

if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}

if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];

for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);

if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}

// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}

return this;
}

Comment and share

7-65 Initialization

  • use literal notaion to initialization
  • convenient for testing
  • js engine will check syntax for you
simple initialization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

var people = [
{
firstname : 'John',
lastname : 'Doe',
address : [
'111 Main St.',
'others'
]
},
{
firstname : 'Jane',
lastname : 'Doe',
greet : function (){
return 'Hi ';
}
}
]

7-66 typeof instanceof

  • typeof : return the type name in String

  • some unexpected result : [], undefined, null

  • instanceof : find in deeper prototype chain, check if the type in the chain

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

var a = 3;
console.log(typeof a);

var b = "Hello";
console.log(typeof b);

var c = {};
console.log(typeof c);

var d = [];
console.log(typeof d); // weird!
console.log(Object.prototype.toString.call(d)); // better!

function Person(name) {
this.name = name;
}

var e = new Person('Jane');
console.log(typeof e);
console.log(e instanceof Person);

console.log(typeof undefined); // makes sense
console.log(typeof null); // a bug since, like, forever...

var z = function() { };
console.log(typeof z);

7-67 Strict Mode

  • optional
  • must be in the top of file or top of the function
  • not every js engine implement strict mode in the same way

strict mode reference

  • 可能問題
    當多個js files合併時(produciton常用),最開始的js file若使用了strict mode,則後面的files都會受到影響
    不能保證其它lib都遵守strict mode
one circumstance that strict mode helps
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//'use strict';

function logNewPerson(){
//'use strict';

var person2;
persom2 = {};
console.log(persom2);
}

var person;

persom = {};
console.log(persom);

Comment and share

4-33 Json and object literal

  • 用xml傳送資料會有多餘且重複的字
  • 嘿~, js object literal 拿來送資料好像不錯用噢~
  • property name “must” be quoted in JSON(In object literal, it could be quoted )
  • JSON is technically a subset of object literal syntax
    -> valid json is also valid js object literal syntax
  • JSON is so popular that js has utilities to tranfer between the two.(JSON.stringtify, JSON.parse)

Comment and share

4-32 Faking Namespace

bigword alert : Namespace

  • a container for variables and functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

greet = 'Hello!';
greet = 'Hola!';

// greet collide
console.log(greet);

var english = {};
var spanish = {};

english.greet = 'Hello!';
spanish.greet = 'Hola!';

english.greetings.greet = 'Hello'; // cannot creating on the fly

/*
var english = {
greeting : {
basic : 'Hello!'
}
};
*/

Comment and share

4-30 Objects and the DOT

  • (computed member access) is a operator
  • . (dot) is a operator too
  • both has left-to-right asscociativity
  • dot is recommended

types of object properties

computed member access
1
2
3
4
5
6
7
8
9
10

var person = new Object();

person["firstname"] = "Tony";
person["lastname"] = "Alicea";

var firstNameProperty = "firstname";

console.log(person);
console.log(person[firstNameProperty]);
dot operator
1
2
3
4
5
6
7
8
9
10
11
12

var person = new Object();

person["firstname"] = "Tony";
person["lastname"] = "Alicea";

console.log(person.firstname);

person.address = new Object();
person.address.stree = "111 Main St.";
person.address.city = "New York";
person.state = "NY";

4-31 Object and object literal

  • {} is NOT a operator
object literal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

/*
var person {};
= var person = new Object();
*/

var Tony = {
firstname : 'Tony',
lastname : 'Alicea',
address : {
stree : '111 Main St.',
city : 'New York',
state : 'NY'
}
};

function gree(person){
console.log('Hi ' + person.firstname);
}

greet(Tony);

// creating object on the fly
greet({
firstname : 'Mary',
lastname : 'Doe'
});

Comment and share

3-28 Default values

  • || operator will return first one could be coerced to true or false
js default value 小技巧
1
2
3
4
5
6
7
8
9
10
11
12
13

function greet(name){
console.log('Hello ' + name);
}

greet(); // 'Hello undefined'

function greet2(name){
name = name || '<Your name here>'
console.log('Hello ' + name);
}

greet2(); // 'Hello <Your name here>'

3-29 Framework aside: Default value

lib1.js
1
2

var libname = 'lib1';
lib2.js
1
2
3
4
5

var libname = 'lib2';

// batter way
// window.libname = window.libname || 'lib2';
app.js
1
2
3

console.log(libname);
//lib2
index.html
1
2
3
4
5
6
7
8
9
10
11
12

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src = lib1.js type="text/javascript"></script>
<script src = lib2.js type="text/javascript"></script>
<script src = app.js type="text/javascript"></script>
</body>
</html>

Comment and share

3-19 Types and javascript

bigword alert : Dynamic typing

  • you don’t tell the engine what type of data a variable holds
  • it figures it out while your code is running

3-20 Primitive types

bigword alert : Primitive type

  • a type of data that represents a single value
  • (not a object)

List of primitive types in javascript

  1. undefined
    lack of existence(note that you shouldn’t set avariable to this)

  2. null
    lack of existence(you can set a variable to this)

  3. boolean
    true or false

  4. number
    floating point number

  5. string
    sequence of characters

  6. symbol
    new feature in ES6, 略

3-21 Operators

bigword alert : operator

  • a special function that is syntactically (written) differently
add operator
1
2

var a = 4 + 3;
  • recall : postfix, prefix, infix

3-22 Operator precedence and associativity

operator precedence and Associativity table

bigword alert : operator precedence

  • which operator function get called first
  • higer precedence wins

bigword alert : associativity

  • when function have the same precedence, what order operator function get called in
  • left-to-right or right-to-left
precedence and associativity
1
2
3
4
5
6
7

var a = 4 + 3 * 5;
// precedence

var b = 4, var c = 5;
a = b = c;
// associativity

3-24 Coercion

bigword alert : Coercion

  • converting a value from one type to another
Coercion
1
2
3
4
5
6
7

var a = 1
var b = '2';

/* bunch of codes */

console.log(a+b);

3-25 Comparison operator

Comparsion result table

  • Recalls : associativity, operator, coercion
try it out
1
2
3
4
5
6
7
8
9
10
11
12
13

console.log(3 < 2 < 1);

/*
3 < 2 < 1 //associativity
false < 1 //coercion
0 < 1 //operator
true

*/

Number(undefined) // NaN
Number(null) // 0
weird equal operator
1
2
3
4
5
6

'3' == 3 //true
false == 0 //true
null == 0 //false, what!?
"" == 0 //true
"" == false //true
  • In javascript, == will do coercion
  • Strict equality (===) is going to save your life !!
  • 99% of the time, use ===

3-27 Existence adn Booleans

how coercion could be useful
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Boolean(undefined); //false
Boolean(null); //false
Boolean(''); //false
Boolean(0) //false
var a;

/*goes internet and looks for a value*/

// a is coercion to boolean
// if a could be 0, addtional comparsion is need
if (a || a === 0){
console.log('Something is there.');
}

Comment and share

2-18 What about asynchronous callback?

bigword alert : asynchronous

  • more than one at a time

  • asking other elements -> asynchronous
  • inside js -> synchronous

Example : Event Queue

  • js engine looks at the queue periodically only when stack is empty
  • browser puts the event asynchronously
  • js run the event handler line by line
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

// long running function
function waitThreeSeconds() {
var ms = 3000 + new Date().getTime();
while (new Date() < ms){}
console.log('finished function');
}

function clickHandler() {
console.log('click event!');
}

// listen for the click event
document.addEventListener('click', clickHandler);


waitThreeSeconds();
console.log('finished execution');

Comment and share

2-14 function invocation and the execution stack

bigword alert : invocation

  • running a function
  • in js, using parenthesis ()

圖解 execution stack

  • 每次function被執行,都會建立新的 execution context,即使是呼叫自己

  • stack 最上層的context正在被執行


2-15 functions, context adn variables

bigword alert : variable environment

  • where the variables live

bigword alert : scope

  • where a variable is available in your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

function b(){
var myvar;
console.log(myvar);
}

function a(){
var myvar = 2;
console.log(myvar);
b();
}

var myvar = 1;
console.log(myvar);
a();
console.log(myvar);


/*
1
2
undefined
1
*/

try to draw a picture below


2-16 Scope Chain

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

function b(){
console.log(myvar);
}

function a(){
var myvar = 2;
b();
}

var myvar = 1;
a();


/*
1
why?
*/

Ans

  • 如果var 不在該execution context,js engine 會到outer environment 找

  • outer environment is depend on where the function sits lecically(set up in creation phase)

  • note : 不是到stack下一層找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19



function a(){
function b(){
console.log(myvar);
}

var myvar = 2;
b();
}

var myvar = 1;
a();


/*
2
*/


2-17 scope ES6 and let

(Recall) bigword alert :scpoe

  • where a variable is available in your code

let

  • block scoping
  • not allow to use the variable (access undefined) until the line ofcode is run

Comment and share

Author's picture

Necisam

author.bio


author.job


Tainan, Taiwan