es6 Symbole入門理解

2022-08-25 14:57:31 字數 2259 閱讀 4071

//我簡單理解這個東西就是可以做唯一標識,也可以不是

var s1 = symbol('s1) //這就是唯一的

var s2 = symbol.for('s2') //這個就不是唯一的了

var obj =

var obj2 = {}

var obj[s1] = 'bbb'

// 阮大師的話我真沒理解啥意思。。。

// 我理解這個就是對原生一些方法的攔截,不執行源生方法改執行自己的,所以如果想實現功能必須自己寫**完成

// 1. hasinstance

class myclass

}[1, 2, 3] instanceof new myclass() // true

//當myclass被當作是否為另外乙個例項的建構函式比較時,hasinstance會執行

// 2. isconcatspreadable

var a = [1, 2]

var b = [3, 4]

var c = a.concat(b) //[1, 2, 3, 4]

b[symbol.isconcatspreadable] = false // 這裡屬性有3個值 undefined和true 這倆是乙個意思, 還有個false就是不分解合併。

a.concat(b) // [1, 2, [3, 4]] // 不分解合併就成這樣了

// 3. species 通過這個函式的返回值來建立例項

class myarray extends array

}let a = new myarray(1,2,3);

a instanceof myarray // true

a instanceof array // true

// 4. match

class mymatcher

}'e'.match(new mymatcher())

// 5. replace

const x = {};

x[symbol.replace] = (...s) => console.log(s);

//能得到這個結果,說明...s結構了2個引數,乙個是'hello',乙個是'world'

'hello'.replace(x, 'world') // ["hello", "world"]

//為了完成替換功能,改了一下demo

const x = {};

x[symbol.replace] = (s1, s2) => ;

console.log('hello __'.replace(x, 'world')) // ["hello", "world"]

// 6. search //搜尋時的 'foobar'.search(new mysearch('foo')) // 0

// 7. split //分割時的 'foobar'.split(new mysplitter('baz'))

// 8. iterator //for..of 解構時的 [...myiterable], for(let value of mycollection) {}

// 9. toprimitive //轉為原始型別的值時會執行 number,string, default

2 * obj // 246

3 + obj // '3default'

obj == 'default' // true

string(obj) // 'str'

// 10. unscopables

//這個東西和with密不可分。

var obj =

//with的作用就是在打括號裡可以直接使用該物件的屬性或方法,

with(obj)

//unscopables,這貨就是不讓你在with裡用。。。僅此而已

//看下 阮大師的案例

// 沒有 unscopables 時

class myclass

}var foo = function() ;

with(myclass.prototype)

// 有 unscopables 時

class myclass

get[symbol.unscopables]() ;}}

var foo = function() ;

with(myclass.prototype)

ES6快速入門

三種語法實現同乙個功能,從而加深對三種語法的運用,最後了解es6的優勢 知識點 常量 作用域 箭頭函式 預設 物件 es5 中常量的寫法 object.defineproperty window,pi2 console.log window.pi2 es6 的常量寫法 const pi 3.1415...

es6入門筆記

常量constconst a 1 a 2 console.log a 報錯 vm6833 2 uncaught typeerror assignment to constant variable.常量唯讀,不可以更改列表專案 es5 es6作用域舉個栗子 es5 function arr 0 4,i...

ES6快速入門

引數配置 promise物件 const 宣告的常量不可改變,宣告時必須初始化 const pi 3.1415926 console.log pi 使用const定義的陣列和物件,其值是可變的,但是不能對其進行重新賦值 const a a 0 1 console.log a 0 輸出1 const ...