第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

数字  +0、-0、NaN都是false,其他都是true
字符串  如果字符串是空的(长度为0)就是false,其他都是true
对象  true

相等操作符号

==

类型x           类型y         结果
null            undefined    true
undefined    null            true
数字           字符串      x==toNumber(y) 
字符串         数字        toNumber(x)==y
布尔值       任何类型    toNumber(x)==y
任何类型     布尔值      x==toNumber(y)
字符串或数字  对象      x==toPrimitive(y)
对象       字符串或数字 toPrimitive(x)==y

没有列在这个列表都会返回false

toNumber toPrimitive

toNumber方法对不同类型返回的结果
undefined     NaN
null            0
布尔值        如果是true返回1,如果是false返回0
数字          对应的数字值
字符串        将字符串解析成数字。如果字符串中包含字母,返回NaN;如果是由数字字符组成的,转换成数字
对象          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                值                                结果
数字         x和y数值相同(不是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));

你可能感兴趣的:(第1章 Javascript简介)