function point(x,y='haha'){}
1.1. 注意
function ha(x,y=1)
const p = new gha(); // uncaught syntaxerror: identifier 'x' has already been declared
1.2. 函式的length屬性function foo( = {})
foo() // undefined 5
length屬性的含義是,該函式預期傳入的引數個數。
指定了預設值以後,函式的length屬性,將返回指定預設值前的引數個數。如果設定了預設值的引數不是尾引數,那麼length屬性也不再計入後面的引數了。
即length屬性會失真。
1.3. 作用域(function (a = 0, b, c) {}).length // 0
(function (a, b = 1, c) {}).length // 1
(function(...args) {}).length // 0
函式呼叫時,函式體內部的區域性變數x影響不到預設值變數x。
請注意下面2個例項let x = 1;
function f(y = x)
f() // 1
var x = 1;
function foo(x = x)
foo() // referenceerror: x is not defined
var x = 1;
function foo(x, y = function() )
foo() // 3
x // 1
1.4 應用var x = 1;
function foo(x, y = function() )
foo() // 2
x // 1
含義:用於獲取函式的多餘引數.- 可以指定引數的預設值;
- 指定引數不得省略(方式1,將預設值設定為丟擲錯誤的函式;方式2 設為undefiend)
rest引數(...變數名)搭配的變數是個陣列
注意:
es2016 做了一點修改,規定只要函式引數使用了預設值、解構賦值、或者擴充套件運算子,那麼函式內部就不能顯式設定為嚴格模式,否則會報錯。function add(...values)
return sum;
}add(2, 5, 3) // 10 非此處是rest引數
add(...[2,5,3]) // 10 陣列可直接用在函式引數中
原因:函式的執行順序:函式引數--》函式體。有時候,引數中使用了非嚴格模式,引數卻能執行,等到函式體才報錯,這樣不合適,故es6直接禁止掉。
'use strict';
function dosomething(a, b = a)
const dosomething = (function () ;
}());
5.1寫法:(引數)=> ***xvar f = function () {};
// es5
f.name // ""
// es6
f.name // "f"
const bar = function baz() {};
// es5
bar.name // "baz"
// es6
bar.name // "baz"
(new function).name // "anonymous"
function foo() {};
foo.bind({}).name // "bound foo"
(function(){}).bind({}).name // "bound "
5.2與rest引數結合若***x 只有一行, ***就是返回值
若***x 超過一行, ***就是函式體,返回值需要自己寫
注意:當***x為時,需要用小括號包一下,以免瀏覽器解析錯誤
應用1: 將函式引數變為陣列
5.3 注意:沒有自己的this物件。可以繫結this物件const numbers = (...nums) => nums;
numbers(1, 2, 3, 4, 5)
// [1,2,3,4,5]
const headandtail = (head, ...tail) => [head, tail];
headandtail(1, 2, 3, 4, 5)
// [1,[2,3,4,5]]
(1)函式體內的this物件,就是定義時所在的物件,而不是使用時所在的物件。即傳了啥,就是啥,和函式體無關。
(2)不可以當作建構函式,也就是說,不可以使用new命令,否則會丟擲乙個錯誤。
(3)不可以使用arguments物件,該物件在函式體內不存在。如果要用,可以用 rest 引數代替。
(4)不可以使用yield命令,因此箭頭函式不能用作 generator 函式。
length屬性,function timer() , 1000);
}var timer = new timer();
settimeout(() => console.log('s1: ', timer.s1), 3100);
settimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0
name屬性
尾呼叫的概念:指某個函式的最後一步是呼叫另乙個函式。
類的作用:通過類生成例項物件;優點,比之前的通過建構函式的方式,清晰、形象。更加像物件導向語言。
1.1建構函式的寫法
1.2 表示式的寫法class haha
lala(){}
...}let shili = new haha();
shili.lala();
注意下constructor方法, 這個是類預設的方法,沒有定義,也可以呼叫。let gaga = class me
lala()
...}let shili = new gaga();
shili.lala();
理解ES6中class語法
function point result point.prototype.add function var num new point add 建立例項並呼叫add方法 console.log num 列印這個方法的返回值1.宣告類 class point add let num new poin...
es6 語法 (正則擴充套件)
es5中常見修飾符是g i es6中新增 y,u exec 方法用於檢索字串中的正規表示式的匹配。test a false console.log u u.test a true 加上u才能被識別 console.log u let s console.log u test s false cons...
ES6 函式擴充套件
函式在js裡是相當重要的一部分了,es6裡也新增了一些函式方法,來看一下 test hello hello world test hello kill hello kill es6增加了函式引數預設值,可以直接在宣告引數的同時賦預設值,但是也可以後面重新賦值 test2 kill 括號內有引數x時,...