Learn Javascript Visually 读书笔记

Imperative programming  

In computer science, imperative programming, as opposed to declarative programming, is a programming paradigm that describes computation in terms of a program state and statements that change the program state. In much the same way as the imperative mood in natural languages expresses commands to take action, imperative programs are a sequence of commands for the computer to perform.

imperative programming  

命令式程度设计


jQuery, Dojo and others are used to extend JavaScript and increase its potential and usefulness. They are libraries of code available for you to simplify some of the more complex commonly used code. After all, JavaScript is very powerful and fast, but writing everything from scratch can be very tedious.


<script type="text/javascript"> alert("It’s best if I sit low.");</script> <!--embed script; 双引号不能用中文输入状态下的双引号-->

JavaScript can be interpreted or compiled. Most modern browsers compile the code before execution.

When you have statements in one line, the first semicolon is required. When you have statements separated by line breaks, semicolons are optional as the line break acts as one.

The brackets hold arrays, braces create object group statements, while parentheses supply parameters, group expressions, and execute functions.

JavaScript also has DYNAMIC TYPES. This means that the same variable can be used as more than one type.

Variable names can start with a letter, underscore or the dollar sign "$".

Declaration is reserving a space in a memory.


The most common unary operators are:a++ , a--; which take the value and then add/subtract 1 to it and assigns it back to the variable. Similar to a = a + 1; or a = a – 1;

++a, --a; which adds/subtract 1 then take the value.


Print out a string and the value of a variable:

var a = 10;

a++;

console.log("The value of a is: " + a);

Or

var a = 10;

a++;

console.log("The value of a is: ", a);

 JavaScript does not have block scope.

Expressions are sets of literals, variables and operators that resolve to a value. So if the line of code gives you a value, then it is an expression. There are two types of expressions: those that assign a value to a variable and those that simply have a value.


Form feed is a page-breaking ASCII control character. It forces the printer to eject the current page and to continue printing at the top of another. Often, it will also cause a carriage return


For loop:

for (i = 0; i < 5; ++i) {

console.log( "The number is " + i);

}

For in loop:

 

var person = {fname:"John", lname:"Doe", age:25};

var text = "";

var x;

for (x in person) {

text += person[x];

}

console.log(text);        

While loop:

var i = 0;                        

while (i < 10) {

console.log("The number is " + i);

i++;

}

Do while loop:

var i = 0;

do {

    console.log("The number is " + i);
    i++;
}

while (i < 10);

When checking source code, you can usually identify arrays in JavaScript because the name is often a plural, like colors instead of color, and so on. This is due to the fact that arrays are a list of things.

//using array

var num = [1,2,3,4,5];

num[0] = "Mike"; //change the first element

num[4] = ["red", "blue", "green"]; //change the last element

alert(num);
//remove the last element of an array

var colors = ["Blue", "Red", "Orange"];

colors.pop();

alert(colors);
//adding an element to the end of an array

var colors = ["Blue", "Red", "Orange"];

colors.push("Yellow");

alert(colors);
//remove the first element of an array

var colors = ["Blue", "Red", "Orange"];

colors.shift();

alert(colors);
//adding an element to the beginning of an array

var colors = ["Blue", "Red", "Orange"];

colors.unshift("Green");

alert(colors);
//sorting an array of strings

var colors = ["Blue", "Red", "Orange"];

alert(colors.sort());
//sorting an array of numbers

var scores = [3, 95, 90, 50, 20, 10];

alert(scores.sort());//this will sort numbers based on their left most number.

alert(scores.sort(function(a, b){return a-b}));//this will sort numbers from small to big

alert(scores.sort(function(a, b){return a-b}).reverse());//reverse an array
//create an empty array

var result = [];
//create the numbers 11 to 23 included

for (var num = 11;num <=23; num++) {

    //add the number to the end of the array every time you run the loop

    result.push(num);

}

//display the content of the array

alert(result);        

//function

var x = myFunction(4, 3); // Function is called, the return value will end up in x

function myFunction(a, b) {

return a + b; // Function returns the product of a and b

}

alert(x);

alert("Sum of 4 and 3 is: "+myFunction(3,4));

//convert centimeter to inch                        

function cm2in(x) {

    var convert = x/2.54;

    return Math.round(convert) + '"';

}

alert(cm2in(16));
//nesting a function inside another function

function foo(a, b) {

    function bar() {
        return a + b;
    }


return bar();

}


var result = foo(1, 2);

console.log(result);

//计算直角三角形的斜边长度

function hypotenuse(a, b) {

function square(x) { return x*x; }

return Math.sqrt(square(a) + square(b)); // sqrt() is a function from the math library

}


var hypotenuse_length = hypotenuse(3,4);

console.log(hypotenuse_length);

JavaScript can change all the HTML elements, attributes, and CSS styles on the page.

Javascript code should be put after the HTML elements that it wants to manipulate.

<script type="text/javascript"> 

function count_h2(){ 

var total_h2=document.getElementsByTagName("h2"); 

alert("total h2 tags are: "+total_h2.length); 

}

</script>


<button onclick="count_h2()">count h2 elements</button>

//function can be called before being declared.

console.log(foo());

function foo() { return 8; }

Function statement is where a statement begins with the word “function”. If not, it’s a function expression.

function functionName(parameters) {

    //code to be executed

}
console.log(Math.pow(2,10));

//raise the number 2 to the power of 10

function power(x) {

var raise= x * x * x * x * x * x * x * x * x * x; // (x10)

return raise;

}

console.log(power(2));//1026
/* In function expression, function name can be omitted in a function expression to create an anonymous function.*/

var variableName = function(parameters) {

    //code to be executed

};

// if you want to refer to the current function inside the function body, then you need to create a named function expression. The name will be local only to the function body.

//Immediately-invoked function expressions.

( function () {

console.log("no need to call me again");

}() );

//The second pair of parentheses at the end invokes the function
//Immediately-invoked function expressions.


var x = function() {

    console.log("no need to call me again");

}();

//The second pair of parentheses at the end calls and closes the function

//if we try to call it later, we get an error:

//x();

//TypeError: x is not a function

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

(function () {
    statements
})();

It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.

The second part creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.

With wrapping the anonymous function inside the parentheses, the JavaScript parses knows to treat it as a function expression and not as a function declaration. If it is treated as a function declaration, then we will need a name for the function to avoid syntax errors, and it will also need to be invoked at some point.

Since the function in our IIFE is a function expression and it is not being assigned to a global variable, no global properties are being created, and thus, all the properties are created locally, so we get local scope.

(function () {

    var aName = "Barry";

console.log(aName);

})();

// Variable name is not accessible from the outside scope

aName // throws "Uncaught ReferenceError: aName is not defined"

// Assigning the IIFE to a variable stores the function's return value, not the function definition itself.

var result = (function () {

    var name = "Barry";

    return name;

})();

// Immediately creates the output:

console.log(result); // "Barry"

JavaScript has function-level scope. The variables inside a function are invisible to the outside. The local scope can “see” the global scope, but the global scope can’t “see” the local scope.

In JavaScript, scope is the set of variables, objects, and functions that you have access to.

Furthermore, objects and functions are also variables in JavaScript.

When you assign a value to a variable that has not been declared, it will automatically become global.

Hoisting is when function and variable declarations are moved to the top of their scope. This is the default behavior of JavaScript.

In JavaScript, a variable can be used before it has been declared.

x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element

elem.innerHTML = x; // Display x in the element

var x; // Declare x
//When you assign a value to a variable that has not been declared, it will automatically become global.

function countApples() {
    sim= 4;
    console.log(sim);
}

var sim;

countApples(sim);//output 4

Since not many developers are familiar with hoisting in JavaScript, it is recommended to declare all variables at the beginning of every scope.

A closure is an inner function that has access to the variables of the outer function.

Closures store references to the variables in the outer function; they do not store the actual values. Closures have access to updating the values of the outer function’s variables.

function showName (firstName, lastName) {

var nameIntro = "Your name is ";

// this inner function has access to the outer function's variables, including the parameter

function makeFullName () {

nameIntro ="我的名字是 "//inner function can change outer function's variable.

return console.log(nameIntro + firstName + " " + lastName);

}

return makeFullName ()

}

showName ("John", "Doe"); // 我的名字是 John Doe

 
function add(x){

    return function(y){

        return x+y;

    };

}

console.log(add(3)(5));//8
<a href="#" onClick="alert('Hi');">Click this link to show a message</a>
<button onclick='getElementById("demo").innerHTML=Date()'>Click me to show what time it is now.</button>

change the content of one element itself, use this.innerHTML instead.

<!-- SHOW HOW MANY TIMES A BUTTON IS CLICKED-->

<!DOCTYPE HTML>

<html>

  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>Increment count when button is clicked</title>

  </head>



  <body>

    <input type="button" value="Count" id="countButton" />



    <p>The button was pressed <span id="displayCount">0</span> times.</p>



    <script type="text/javascript">

      var count = 0;

      var button = document.getElementById("countButton");

      var display = document.getElementById("displayCount");



      button.onclick = function(){

        count++;

        display.innerHTML = count;

      }

    </script>

  </body>

</html>
//create an empty object

var apple = {};

//create an object and add properties to it
apple= {
    name: "Machintosh",
    color: "Green",
    weight: 100,
    //add method
    display:function(){alert("I weight "+this.weight+" g.");}
};

console.log(apple);

//property change with “.” Dot notation.
apple.color = "Red";

//add the new smell property
apple.smell = "Fresh";

console.log(apple);                

//call the method of the apple object
apple.display();
//result: I weight 100g

//get the value of a propertu
var getValue = apple.weight;
console.log(getValue);   

var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};                

console.log(person);
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

console.log(person);
/*The value of “this” when using in a function is the object that the function belongs to. However, when “this” is used in an object, it is the object itself. “this” is a keyword, not a variable, and so its value cannot be changed. */
 

function person(first, last, age, eyecolor) {

    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;

    this.changeName = function (name) {
        this.lastName = name;
    }

}


var myFather = new person("John", "Doe", 50, "blue");
console.log(myFather);

var myMother = new person("Sally", "Rally", 48, "green");
console.log(myMother);        

myMother.changeName("Doe");
console.log(myMother);
//using built-in string method

var message = "Hello world!";

var x = message.toUpperCase();

console.log(x);   
var Fruit = function Fruit(name, color) {

    this.name = name; //property
    this.color = color;4. //Method
    this.info = function() {return "I am a " +this.color + " "  + this.name};

}


var Cherry = new Fruit("cherry", "red");
console.log(Cherry);
console.log(Cherry.info());
var user = function (name) {
    this.name = name;
};

var john = new user("John");
console.log(john);
var Fruit = function Fruit(name, color) {
    this.name = name; //property
    this.color = color;
    //Method
    this.info = function() {return "I am a " +this.color + " " + this.name};

}

//This adds a property to the Fruit prototype object
Fruit.prototype.price = 100;

//add new methods to an existing prototype
Fruit.prototype.cost = function() {
    return 'This ' +this.name+' cost ' + this.price;
};


var pear = new Fruit('pear', 'golden');
console.log(pear.price);
//100

console.log(pear.info());
//I am a golden pear

console.log(pear.cost());
//This pear cost 100
var Counter = function(){
    Counter.prototype.count++;
};

Counter.prototype.count = 0;

new Counter();
new Counter();
console.log((new Counter()).count);//3

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值