JavaScript study notes (3) --- function, standard objects

JavaScript: function, standard objects

Acquaintance function

Function on and Java method is the same, plainly, is a collection of statements, we can be extracted to achieve reuse!

In JavaScript, define the following functions:

function abs(x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

Defined above ABS () function is as follows:

  • functionHe pointed out that this is a function definition;
  • absIs the name of the function;
  • (x)Function parameters are listed in parentheses, a plurality of parameters, the partition;
  • { ... }Code between the body of the function, may comprise several statements, or even without any statement.

Please note that statements inside the function body at the time of execution, once executed to return, the function implementation is completed, and the results returned. Thus, the internal function is determined by the conditions and the cycle can achieve very complex logic.

If no return statement, the function will return the results of execution after completion, but the result is undefined.

Since the function of JavaScript is an object, as defined above abs () function is actually a function object, and function names abs can be considered variable to point to the function.

Thus, the second function is defined as follows:

var abs = function (x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
};

In this manner, function (x) {...} is an anonymous function, it does not function name. However, this anonymous function assigned to the variable abs, therefore, by the variable abs you can call the function.

Both the definition of fully equivalent, attention to the second way in accordance with the complete syntax need to add at the end of a function body; indicates the end of an assignment statement.

When you call the function, passing parameters in order to:

abs(10); // 返回10
abs(-9); // 返回9

Since JavaScript allows you to pass arbitrary parameters without affecting the call, so the incoming parameters defined by many parameters than there is no problem, although the internal functions do not require these parameters:

abs(10, 'blablabla'); // 返回10
abs(-9, 'haha', 'hehe', null); // 返回9

Incoming less than the defined parameters is not a problem:

abs(); // 返回NaN

To avoid receiving undefined, you can check the parameters:

function abs(x) {
    //类型比较,和抛出异常~
    if (typeof x !== 'number') {
        throw 'Not a number';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

arguments only inside the function to work, and never point to all the parameters of the current function of the incoming caller. Use arguments, you can get all the parameters passed by the caller. In other words, even if the function does not define any parameters, you can still get the value of the parameter:

function abs() {
    if (arguments.length === 0) {
        return 0;
    }
    var x = arguments[0];
    return x >= 0 ? x : -x;
}

abs(); // 0
abs(10); // 10
abs(-9); // 9

rest parameters

ES6 standard introduces rest parameters:

function foo(a, b, ...rest) {
    console.log('a = ' + a);
    console.log('b = ' + b);
    console.log(rest);
}

foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ]

foo(1);
// 结果:
// a = 1
// b = undefined
// Array []

rest parameters can only be written in the final, with ... logo front, seen from the operating results, the argument passed to bind a, b, the extra variable parameters to rest in an array, so we no longer need arguments get all the parameters.

If the argument passed even the normal definition of the parameters did not fill, it does not matter, rest parameter receives an empty array (note that not undefined).

Variable Scope and deconstruction assignment

In JavaScript, with variable var stated there is actually scope.

If a variable function declaration inside the body, the scope of this variable is a function of the whole body, not the variable is referenced in vitro function:

'use strict';

function foo() {
    var x = 1;
    x = x + 1;
}

x = x + 2; // ReferenceError! 无法在函数体外引用变量x

If two different functions each affirmed with a variable, the variable only work in their function in vivo. In other words, the same variables are different internal functions independent of each other, independently of each other:

'use strict';

function foo() {
    var x = 1;
    x = x + 1;
}

function bar() {
    var x = 'A';
    x = x + 'B';
}

Since the JavaScript function can be nested, at this time, internal functions can access external variable defined function, vice-versa:

'use strict';

function foo() {
    var x = 1;
    function bar() {
        var y = x + 1; // bar可以访问foo的变量x!
    }
    var z = y + 1; // ReferenceError! foo不可以访问bar的变量y!
}

If the variable names inside functions and external functions of the same name how to do? To test:

function foo() {
    var x = 1;
    function bar() {
        var x = 'A';
        console.log('x in bar() = ' + x); // 'A'
    }
    console.log('x in foo() = ' + x); // 1
    bar();
}

foo();

This shows that the JavaScript function from the function definition itself starts when looking variables and look from "inside" to "outside." If the internal variables and function defines the external function of the same name, then the variable inside the function of "masking" function of the external variables.

Variable lift

The JavaScript function definition has a feature that scans the entire body of the function statement, all variables declared "upgrade" to the top of the function:

'use strict';

function foo() {
    var x = 'Hello, ' + y;
    console.log(x);
    var y = 'Bob';
}

foo();

Although strict mode, but the statement var x = 'Hello,' + y; not given, because the variable y at a later affirmed. However console.log display Hello, undefined, explanatory variables y is undefined. This is because the JavaScript engine automatically enhance the declaration of variables y, but will not improve the assignment variable y.

For the above foo () function, JavaScript code corresponds engines see:

function foo() {
    var y; // 提升变量y的申明,此时y为undefined
    var x = 'Hello, ' + y;
    console.log(x);
    y = 'Bob';
}

Because of this strange "feature" JavaScript, and when we function internally defined variables, strictly abide by "internal function first declare all variables," the rule. The most common approach is to declare all variables within the function used with a var:

function foo() {
    var
        x = 1, // x初始化为1
        y = x + 1, // y初始化为2
        z, i; // z和i为undefined
    // 其他语句:
    for (i=0; i<100; i++) {
        ...
    }
}

Global scope

Is not within any defined variable will function has global scope. In fact, JavaScript has a default global object window, the global scope is actually bound to a property of the window:

'use strict';

var course = 'Learn JavaScript';
alert(course); // 'Learn JavaScript'
alert(window.course); // 'Learn JavaScript'

Therefore, direct access to the global variables and access window.course course is exactly the same.

You might guess, since the function is defined in two ways, in a variable manner var foo = function () {} function is actually defined by a global variable, therefore, the top-level definition of the function is also considered a global variable, and tie fixed to the window object:

'use strict';

function foo() {
    alert('foo');
}

foo(); // 直接调用foo()
window.foo(); // 通过window.foo()调用

Further hazard a guess, every time we directly call the alert () function is actually a variable window of:

window.alert('调用window.alert()');
// 把alert保存到另一个变量:
var old_alert = window.alert;
// 给alert赋一个新函数:
window.alert = function () {}
alert('无法用alert()显示了!');
// 恢复alert:
window.alert = old_alert;
alert('又可以用alert()了!');

Local scope

Since the variable scope of JavaScript is actually an internal function, and so we are in a for loop statement block is not possible to define variables with local scope of:

'use strict';

function foo() {
    for (var i=0; i<100; i++) {
        //
    }
    i += 100; // 仍然可以引用变量i
}

In order to solve the block-level scope, ES6 introduced a new keyword let, alternatively using let var can declare a variable block-level scope:

'use strict';

function foo() {
    var sum = 0;
    for (let i=0; i<100; i++) {
        sum += i;
    }
    // SyntaxError:
    i += 1;
}

constant

As the var and let affirm that variable, if you want to declare a constant, before ES6 does not work, we usually use all uppercase variables to represent "This is a constant, not to modify its value":

var PI = 3.14;

ES6 standard introduces a new keyword to define the constant const, const and let having block-level scope:

'use strict';

const PI = 3.14;
PI = 3; // 某些浏览器不报错,但是无效果!
PI; // 3.14

method

The method of binding function in an object, the object referred to.

In JavaScript, objects are defined like this:

var xiaoming = {
    name: '小明',
    birth: 1990,
    age: function () {
        var y = new Date().getFullYear();
        return y - this.birth;
    }
};

xiaoming.age; // function xiaoming.age()
xiaoming.age(); // 今年调用是25,明年调用就变成26了

Bound to function on an object called methods, and general function also lacks distinction, but it uses a keyword within this, what is this stuff that?

Within a method, this is a special variable, it always points to the current object is xiaoming this variable. So, this.birth can get xiaoming property of birth.

Standard objects

In the JavaScript world, everything is an object.

But some objects or other objects are not the same. In order to distinguish the type of object, we get the object type with typeof operator, it always returns a string:

typeof 123; // 'number'
typeof NaN; // 'number'
typeof 'str'; // 'string'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof Math.abs; // 'function'
typeof null; // 'object'
typeof []; // 'object'
typeof {}; // 'object'

Date

In JavaScript, Date object is used to indicate the date and time. To get the current time, use:

var now = new Date();
now; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST)
now.getFullYear(); // 2015, 年份
now.getMonth(); // 5, 月份,注意月份范围是0~11,5表示六月
now.getDate(); // 24, 表示24号
now.getDay(); // 3, 表示星期三
now.getHours(); // 19, 24小时制
now.getMinutes(); // 49, 分钟
now.getSeconds(); // 22, 秒
now.getMilliseconds(); // 875, 毫秒数
now.getTime(); // 1435146562875, 以number形式表示的时间戳

Note that the current time is the time the browser native operating system acquired from, it is not necessarily accurate, because the user can set the current time to any value.

If you want to create a specified date and time of the Date object, you can use:

var d = new Date(2015, 5, 19, 20, 15, 30, 123);
d; // Fri Jun 19 2015 20:15:30 GMT+0800 (CST)

You may observe a place very, very pit father, JavaScript is the month range is represented by an integer from 0 to 11, 0 for January, 1 February ...... so be expressed in June, we passed is 5! This is definitely the designers of JavaScript brain was pumping a bit, but now it has been impossible to repair.

Time Date object always represented by a browser's time zone display, but we can only display the local time, UTC time can also be displayed after adjustment:

var d = new Date();
d.toLocaleString(); 
d.toUTCString(); 

JSON

JSON is JavaScript Object Notation acronym, which is a data exchange format.

Before JSON appeared, we have been using XML to pass data. Because XML is a plain text format, so it is suitable for exchanging data over the network. XML itself is not complicated, but later with a lot of complex specifications DTD, XSD, XPath, XSLT, etc., any normal XML software developers encounter will feel a big head, and finally we found that even if you are trying to study a few months, it may not ever know XML specification.

Finally, the software engineer day in 2002, Douglas Crockford (Douglas Crockford) students in order to save trapped in dire straits while being fooled a few long-term enterprise software giant, the invention of this ultra-lightweight JSON data Interchange format.

And, JSON also dead set character set must be UTF-8, it represents a multi-language no problem. In order to unify parsing JSON string provisions must be enclosed in double quotes "", Object keys must use double quotes "."

Since JSON is very simple, and soon swept the Web world, and become the ECMA standard. Nearly all programming languages ​​have JSON parsing libraries in JavaScript, we can directly use JSON, because the built-in JavaScript parsing of JSON.

The JSON any JavaScript object becomes, the object is to sequence JSON format into a string, so that it can be transmitted to other computers via a network.

If we receive a JSON string format, just take it deserialized into a JavaScript object, you can use the object directly in JavaScript.

In the JavaScript language, everything is an object. Thus, any type of support JavaScript can be represented by the JSON, such as strings, numbers, objects, arrays and the like. Look at his request and syntax:

  • Objects are represented as key-value pairs of data separated by a comma
  • Save Object braces
  • Save array square brackets

JSON key-value pair wording is one way to save the JavaScript object, and also similar JavaScript object, key / value pair combination EDITORIAL keys and double quotation marks "" package, colon: the partition, and then followed by value:

{"name": "QinJiang"}
{"age": "3"}
{"sex": "男"}

A lot of people do not know the relationship between JSON and JavaScript objects, and even anyone who is unclear. In fact, it can be understood:

  • JSON JavaScript object string representation, which represent text information using a JS object is essentially a string.

    var obj = {a: 'Hello', b: 'World'}; //这是一个对象,注意键名也是可以使用引号包裹的
    var json = '{"a": "Hello", "b": "World"}'; //这是一个 JSON 字符串,本质是一个字符串

JSON and JavaScript object system conversion

  • To achieve the JSON string into a JavaScript object, using the JSON.parse () Method:

    var obj = JSON.parse('{"a": "Hello", "b": "World"}'); 
    //结果是 {a: 'Hello', b: 'World'}
  • To achieve the conversion from a JavaScript object JSON string using the JSON.stringify () Method:

    var json = JSON.stringify({a: 'Hello', b: 'World'});
    //结果是 '{"a": "Hello", "b": "World"}'

On the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON_秦疆</title>
</head>
<body>

<script type="text/javascript">
    //编写一个js的对象
    var user = {
        name:"秦疆",
        age:3,
        sex:"男"
    };
    //将js对象转换成json字符串
    var str = JSON.stringify(user);
    console.log(str);
    
    //将json字符串转换为js对象
    var user2 = JSON.parse(str);
    console.log(user2.age,user2.name,user2.sex);

</script>

Guess you like

Origin www.cnblogs.com/xjtu-lyh/p/12392308.html