第1章 Javascript簡介

//變量作用域

var myVariable = 'global';
myOtherVariable = 'global';

function myFunction(){
    var myVariable = 'local';
    return myVariable;
}

function myOtherFunction(){
    myOtherVariable = 'local';
    return myOtherVariable;
}

console.log(myVariable);   //{1}
console.log(myFunction()); //{2}

console.log(myOtherVariable);   //{3}
console.log(myOtherFunction()); //{4}
console.log(myOtherVariable);   //{5}

global
local
global
local
local

/* Bitwise operators */

console.log('5 & 1:', (5 & 1)); //same as 0101 & 0001 (result 0001 / 1)
console.log('5 | 1:', (5 | 1)); //same as 0101 | 0001 (result 0101 / 5)
console.log('~ 5:', (~5)); //same as ~0101 (result 1010 / 10)
console.log('5 ^ 1:', (5 ^ 1)); //same as 0101 ^ 0001 (result 0100 / 4)
console.log('5 << 1:', (5 << 1)); //same as 0101 << 1 (result 1010 / 10)
console.log('5 >> 1:', (5 >> 1)); //same as 0101 >> 1 (result 0010 / 2)

/* typeOf */

console.log('typeof num:', typeof num);
console.log('typeof Packt:', typeof 'Packt');
console.log('typeof true:', typeof true);  //boolean
console.log('typeof [1,2,3]:', typeof [1,2,3]); //object
console.log('typeof {name:John}:', typeof {name:'John'}); //object

/* delete */

var myObj = {name: 'John', age: 21};  //boolean
delete myObj.age;
console.log(myObj); //Object {name: "John"}

//true or false

function testTruthy(val){
    return val ? console.log('truthy') : console.log('falsy');
}

testTruthy(new Boolean(false)); //true (object is always true)
testTruthy(new String('')); //true (object is always true)

testTruthy(-1); //true
testTruthy(NaN); //false
testTruthy(new Number(NaN)); //true (object is always true)

testTruthy({}); //true (object is always true)

var obj = {name:'John'};
testTruthy(obj); //true
testTruthy(obj.name); //true
testTruthy(obj.age); //age (prop does not exist) //false

數(shù)字  +0、-0嫂粟、NaN都是false娇未,其他都是true
字符串  如果字符串是空的(長度為0)就是false,其他都是true
對象  true

相等操作符號

==

類型x           類型y         結果
null            undefined    true
undefined    null            true
數(shù)字           字符串      x==toNumber(y) 
字符串         數(shù)字        toNumber(x)==y
布爾值       任何類型    toNumber(x)==y
任何類型     布爾值      x==toNumber(y)
字符串或數(shù)字  對象      x==toPrimitive(y)
對象       字符串或數(shù)字 toPrimitive(x)==y

沒有列在這個列表都會返回false

toNumber toPrimitive

toNumber方法對不同類型返回的結果
undefined     NaN
null            0
布爾值        如果是true返回1星虹,如果是false返回0
數(shù)字          對應的數(shù)字值
字符串        將字符串解析成數(shù)字忘蟹。如果字符串中包含字母飒房,返回NaN;如果是由數(shù)字字符組成的媚值,轉換成數(shù)字
對象          Number(toPrimitive(vale))

toPrimitive方法對不同類型返回的結果
對象          如果對象的valueof方法的結果是原始值狠毯,返回原始值;如果對象的toString方法返回原始值褥芒,就返回這個值嚼松;其他情況都返回一個錯誤

//Packt == true

console.log('packt' ? true : false);
//outputs true

console.log('packt' == true);
//1 - converts Boolean using toNumber
//'packt' == 1
//2 - converts String using toNumber
//NaN == 1
//outputs false

console.log('packt' == false);
//1 - converts Boolean using toNumber
//'packt' == 0
//2 - converts String using toNumber
//NaN == 0
//outputs false

console.log([0] == true);
//1 - converts Boolean using toNumber
//[0] == 1
//2 - converts Object using toPrimitive
//2.1 - [0].valueOf() is not primitive
//2.2 - [0].toString is 0
//0 == 1
//outputs false  

===

類型x                值                                結果
數(shù)字         x和y數(shù)值相同(不是NaN)        true
字符串     x和y是相同的字符                 true
布爾值     x和y都是true或false               false
對象         x和y引用同一個對象             true

x和y類型不同  false

console.log('packt' === true); //false

console.log('packt' === 'packt'); //true

var person1 = {name:'John'};
var person2 = {name:'John'};
console.log(person1 === person2); //false, different objects

面向對象編程

/* Object example 1 */

var obj = new Object();

/* Object example 2 */

var obj = {};

obj = {
    name: {
        first: 'Gandalf',
        last: 'the Grey'
    },
    address: 'Middle Earth'
};

/* Object example 3 */

function Book(title, pages, isbn){
    this.title = title;
    this.pages = pages;
    this.isbn = isbn;
    this.printIsbn = function(){
        console.log(this.isbn);
    }
}

var book = new Book('title', 'pag',  'isbn');

console.log(book.title); //outputs the book title

book.title = 'new title'; //update the value of the book title

console.log(book.title); //outputs the updated value

Book.prototype.printTitle = function(){
    console.log(this.title);
};

book.printTitle();

book.printIsbn();

es6

let

//******* EcmaScript 6: let and const keywords
// EcmaScript 6 Constants
const PI = 3.141593;
//PI = 3.0; //throws error
console.log(PI);

//******* EcmaScript 6: let is the new var
var framework = 'Angular';
var framework = 'React';
console.log(framework);

let language = 'JavaScript!';
//let language = 'Ruby!'; //throws error
console.log(language);

//******* EcmaScript 6: variables scope
let movie = 'Lord of the Rings';
//var movie = 'Batman v Superman'; //throws error, variable movie already declared

function starWarsFan(){
    let movie = 'Star Wars';
    return movie;
}

function marvelFan(){
    movie = 'The Avengers';
    return movie;
}

function blizzardFan(){
    let isFan = true;
    let phrase = 'Warcraft';
    console.log('Before if: ' + phrase);
    if (isFan){
        let phrase = 'initial text';
        phrase = 'For the Horde!';
        console.log('Inside if: ' + phrase);
    }
    phrase = 'For the Alliance!';
    console.log('After if: ' + phrase);
}

console.log(movie);
console.log(starWarsFan());
console.log(marvelFan());
console.log(movie);
blizzardFan();

// Template literals

var book = {
    name: 'Learning JavaScript DataStructures and Algorithms'
};

console.log(`You are reading ${book.name}.,
    and this is a new line`);

//ES6: arrow functions

let circleArea = (r) => {
    const PI = 3.14;
    let area = PI * r * r;
    return area;
}
console.log(circleArea(2));

let circleArea2 = (r) => 3.14 * r * r;
console.log(circleArea2(2));

//******* EcmaScript 6: Default Parameter Values

function sum (x = 1, y = 2, z = 3) {
    return x + y + z
};
console.log(sum(4,2)); //outpus 9

//function above is the same as
function sum2 (x, y, z) {
    if (x === undefined)
        x = 1;
    if (y === undefined)
        y = 2;
    if (z === undefined)
        z = 3;
    return x + y + z;
};
console.log(sum2(4,2)); //outpus 10

//******* EcmaScript 6: spread operator ('...')
var params = [3, 4, 5];
console.log(sum(...params));

var numbers = [1, 2, ...params]; //pushing values into array
console.log(numbers);

//******* EcmaScript 6: rest parameter ('...')
function restParamaterFunction (x, y, ...a) {
    return (x + y) * a.length;
}
console.log(restParamaterFunction(1, 2, "hello", true, 7)); // outputs 9;

//code above is the same as ES5:
function restParamaterFunction2 (x, y) {
    var a = Array.prototype.slice.call(arguments, 2);
    return (x + y) * a.length;
};
console.log(restParamaterFunction2(1, 2, "hello", true, 7));

// Destructuring Assignment + Property Shorthand

  var [x, y] = ['a', 'b'];
  var obj = { x, y };
  console.log(obj); // { x: "a", y: "b" }

  [x, y] = [y, x];
  var temp = x;
  x = y;
  y = temp;

  //code above is the same as
  var x = 'a';
  var y = 'b';
  var obj2 = { x: x, y: y };
  console.log(obj2); // { x: "a", y: "b" }


  // Method Properties
  var hello = {
      name : 'abcdef',
      printHello(){
          console.log('Hello');
      }
  }
  console.log(hello.printHello());

  //code above is the same as:
  var hello2 = {
      name: 'abcdef',
      printHello: function printHello() {
          console.log('Hello');
      }
  };
  console.log(hello2.printHello());

// ES6 classes

class Book {
    constructor (title, pages, isbn) {
        this.title = title;
        this.pages = pages;
        this.isbn = isbn;
    }
    printIsbn(){
        console.log(this.isbn);
    }
}

let book = new Book('title', 'pag',  'isbn');

console.log(book.title); //outputs the book title

book.title = 'new title'; //update the value of the book title

console.log(book.title); //outputs the book title


//inheritance
class ITBook extends Book {

    constructor (title, pages, isbn, technology) {
        super(title, pages, isbn);
        this.technology = technology;
    }

    printTechnology(){
        console.log(this.technology);
    }
}

let jsBook = new ITBook('Learning JS Algorithms', '200', '1234567890', 'JavaScript');

console.log(jsBook.title);
console.log(jsBook.printTechnology());

//getter and setters
class Person {

    constructor (name) {
        this._name = name;
    }

    get name() {
        return this._name;
    }

    set name(value) {
        this._name = value;
    }
}

let lotrChar = new Person('Frodo');
console.log(lotrChar.name);
lotrChar.name = 'Gandalf';
console.log(lotrChar.name);

lotrChar._name = 'Sam';
console.log(lotrChar.name);


//using symbols for private atributes

var _name = Symbol();
class Person2 {

    constructor (name) {
        this[_name] = name;
    }

    get name() {
        return this[_name];
    }

    set name(value) {
        this[_name] = value;
    }
}

let lotrChar2 = new Person2('Frodo');
console.log(lotrChar2.name);
lotrChar2.name = 'Gandalf';
console.log(lotrChar2.name);

console.log(Object.getOwnPropertySymbols(lotrChar2));
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市锰扶,隨后出現(xiàn)的幾起案子献酗,更是在濱河造成了極大的恐慌,老刑警劉巖坷牛,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件罕偎,死亡現(xiàn)場離奇詭異,居然都是意外死亡京闰,警方通過查閱死者的電腦和手機颜及,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蹂楣,“玉大人俏站,你說我怎么就攤上這事∪粒” “怎么了肄扎?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長赁酝。 經常有香客問我犯祠,道長,這世上最難降的妖魔是什么酌呆? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任雷则,我火速辦了婚禮,結果婚禮上肪笋,老公的妹妹穿的比我還像新娘月劈。我一直安慰自己,他們只是感情好藤乙,可當我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布猜揪。 她就那樣靜靜地躺著,像睡著了一般坛梁。 火紅的嫁衣襯著肌膚如雪而姐。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天划咐,我揣著相機與錄音拴念,去河邊找鬼钧萍。 笑死,一個胖子當著我的面吹牛政鼠,可吹牛的內容都是我干的风瘦。 我是一名探鬼主播,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼公般,長吁一口氣:“原來是場噩夢啊……” “哼万搔!你這毒婦竟也來了?” 一聲冷哼從身側響起官帘,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤瞬雹,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后刽虹,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酗捌,經...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年涌哲,在試婚紗的時候發(fā)現(xiàn)自己被綠了胖缤。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡膛虫,死狀恐怖,靈堂內的尸體忽然破棺而出钓猬,到底是詐尸還是另有隱情稍刀,我是刑警寧澤,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布敞曹,位于F島的核電站账月,受9級特大地震影響,放射性物質發(fā)生泄漏澳迫。R本人自食惡果不足惜局齿,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望橄登。 院中可真熱鬧抓歼,春花似錦、人聲如沸拢锹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽卒稳。三九已至蹋半,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間充坑,已是汗流浹背减江。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工染突, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人辈灼。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓份企,卻偏偏與公主長得像,于是被迫代替她去往敵國和親茵休。 傳聞我的和親對象是個殘疾皇子薪棒,可洞房花燭夜當晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內容