JavaScript --- function

1. Defined Functions

A defined way

1. The absolute value function

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

Once executed on behalf return to the function ends and returns the result!

If no return, executing the function will return a result, the result is undefined

Second way is defined

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

function (x) {....} This is an anonymous function. However, you can assign the result to abs, you can call the function by abs!

Second way and a way equivalent!

call function

abs(10)  //10
abs(-10) //10

Parameter Problem: javaScript can pass any parameters, the parameters may not pass ~

var abs = function(x){
    //手动抛出异常来判断
    if (typeof x!== 'number') {
        throw 'Not a Number';
    }
    if(x>=0){
        return x;
    }else{
        return -x;
    }

}

arguments

argumentsIs a keyword complimentary JS;

Representatives passed in all parameters, is an array!

var abs = function(x){

    console.log("x=>"+x);

    for (var i = 0; i<arguments.length;i++){
        console.log(arguments[i]);
    }

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

}

Question: arguments contains all the parameters, we sometimes want to use the extra parameters to append operation. Need to exclude existing parameters -

rest

before:

if (arguments.length>2){
    for (var i = 2; i<arguments.length;i++){
		//。。。。
    } 
} 

ES6 new features introduced, in addition to obtaining all parameters - parameters that have been defined ....

function aaa(a,b,...rest) {
    console.log("a=>"+a);
    console.log("b=>"+b);
    console.log(rest);
}

rest parameters can only write in the final surface, it must be used ... to identify.

2. The scope of variables

In javascript, var actual variable is defined scope.

Suppose statement in the function body, the function can not be used in vitro - (To achieve non then can look back 闭包)

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

x = x + 2; //Uncaught ReferenceError: x is not defined

If the two functions use the same variable name, as long as the internal function, not conflict

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

function yy1() {
    var x = 'A';
    x = x + 1;
}

Internal functions can access external member function, not vice versa

function yy() {
    var x = 1;

    // 内部函数可以访问外部函数的成员,反之则不行
    function yy2() {
        var y = x + 1;  // 2
    }

    var z = y + 1; // Uncaught ReferenceError: y is not defined
}

Assume that the variables inside the function variables and external functions of the same name!

function yy() {
    var x = 1;

    function yy2() {
        var x = 'A';
        console.log('inner'+x); // outer1
    }
    console.log('outer'+x); //innerA
    yy2()

}

yy()

Suppose in JavaScript functions for variables from their own functions - start, '' the 'variable with' to 'outside' look. Suppose that the external variable function of the same name exists, the internal function of shielding external function.

To enhance the scope of variables

function yy() {
    var x = "x" + y;
    console.log(x);
    var y = 'y';
}

The results: xundefined

Description; js execution engine automatically enhance the declaration of y, but will not improve the assignment variable y ';

function qj2() {
    var y;

    var x = "x" + y;
    console.log(x);
    y = 'y';
}

This is the beginning of JavaScript build on existing properties. Develop specifications: all variables are defined at the head of the function, not misplacing easy code maintenance;

function yy2() {
    var x = 1,
        y = x + 1,
        z,i,a; //undefined

    // 之后随意用
}

Global Functions

//全局变量
x = 1;

function f() {
    console.log(x);
}
f();
console.log(x);

Global object window

var x = 'xxx';
alert(x);
alert(window.x); // 默认所有的全局变量,都会自动绑定在 window对象下;

alert () function itself is a windowvariable;

var x = 'xxx';

window.alert(x);

var old_alert = window.alert;

//old_alert(x);

window.alert = function () {

};
// 发现 alert() 失效了
window.alert(123);

//恢复
window.alert =  old_alert;
window.alert(456);

Javascript is actually only a global scope, any variable (function can also be considered variable), assuming that is not found in the function scope, will find out, if not found in global scope, error RefrenceError

specification

Since all of our global variables are bound to our window. If different js files, use the same global variables, conflict -> If you can reduce conflict?

// 唯一全局变量
var KuangApp = {};

// 定义全局变量
KuangApp.name = 'yy';
KuangApp.add = function (a,b) {
    return a + b;
}

Put all your code into their own unique name space definition, reducing the global problem of naming conflicts -

jQuery

Let local scope

function aaa() {
    for (var i = 0; i < 100; i++) {
        console.log(i)
    }
    console.log(i+1); //问题? i 出了这个作用域还可以使用
}

ES6 let keyword, local scope resolve conflicts!

function aaa() {
    for (let i = 0; i < 100; i++) {
        console.log(i)
    }
    console.log(i+1); //Uncaught ReferenceError: i is not defined
}

I suggest that you are used letto define a local variable scope;

Constant const

Before ES6, how to define constants: Only use all capital letters named variable is constant; recommended not to modify this value

var PI = '3.14';

console.log(PI);
PI = '213'; //可以改变这个值
console.log(PI);

In ES6 introduced the constant keyword const

const PI = '3.14'; // 只读变量
console.log(PI);
PI = '123'; // TypeError: Assignment to constant variable.
console.log(PI);

3. Methods

Definition method

The method is to function in an object inside the object are only two things: the properties and methods

var yy = {
    name: '洋',
    bitrh: 2000,
    // 方法
    age: function () {
        // 今年 - 出生的年
        var now = new Date().getFullYear();
        return now-this.bitrh;
    }
}
//属性
yy.name
//方法,一定要带  ()
yy.age() 

this. What representatives? Apart above code see ~

function getAge() {
    // 今年 - 出生的年
    var now = new Date().getFullYear();
    return now-this.bitrh;
}

var yy = {
    name: '洋',
    bitrh: 2000,
    age: getAge
}

// yy.age() ok
// getAge()  NaN   window

this is not the point, is that it points to the default object calls;

apply

In js can control this point!

function getAge() {
    // 今年 - 出生的年
    var now = new Date().getFullYear();
    return now-this.bitrh;
}

var yy = {
    name: '洋',
    bitrh: 2000,
    age: getAge
};

var xiaoming = {
    name: '小明',
    bitrh: 2000,
    age: getAge
};

// yy.age() ok

getAge.apply(xiaoming,[]);// this,指向了 yy,参数为空
Published 39 original articles · won praise 1 · views 537

Guess you like

Origin blog.csdn.net/love_to_share/article/details/103925683