You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionfn(){console.log(this);}fn();// this指向windownewfn();// this指向fn本身constobj={a: 123};constbindObj=fn.bind(obj);newbindObj()// 覆蓋原先的this(obj),還是指向fn本身newfn().bind(obj)// TypeError: (intermediate value).bind is not a function ... 無法在new時binding// es6 class也是一樣的classfn{constrcutor(){console.log(this)}}fn();// TypeError: Class constructor test cannot be invoked without 'new' ...newfn();// this指向fn本身
constobj={};Object.defineProperty(obj,'a',{writable: false// 不能改寫});obj.a=3;// 結果obj.a還是2,且在嚴格模式下會是TypeError: Cannot assign to read only property 'a' of object
constobj={a: 123};Object.freeze(obj);obj.b=2// undefined, 若在嚴格模式則回傳TypeError: Cannot add property b, object is not extensibleobj.a=234;// 結果obj.a還是234,且在嚴格模式下會是TypeError: Cannot assign to read only property 'a' of object
參考文章 You Don't Know JS: this & Object Prototypes
關於
this
什麼是
this
如何判斷this綁定的位置
new
建構子時,會強制將this
指向被new
的函式bind
,call
,apply
可以將this
強制轉為輸入的參數context object
的則以context object
的環境為this
this
通常為global
, 若為嚴格模式,則this
為undefined
使用
new
建構子時,會強制將this
指向被new
的函式使用
bind
,call
,apply
可以將this
強制轉為輸入的參數呼叫時有
context object
的則以context object
的環境為this
沒有上述條件的,默認的
this
通常為global
, 若為嚴格模式,則this
為undefined
關於屬性描述符 (Property Descriptors)
獲得Object的屬性
Object.getOwnPropertyDescriptor
定義Object的屬性
Object.defineProperty
可寫性 (Writable)
可配置性 (Configurable)
可枚聚性 (Enumerable)
防止擴展 (PreventExtensions)
封印 (Seal)
凍結 (Freeze)
存在性 (Existence)
Object的其他應用
關於prototype
難以捉模的
prototype
釐清
prototype
之間的關係A instanceof B
代表B.prototype
是否在A
的prototype chain
中__proto__
代表該Object
指向的prototype位置prototype
不為人知的設定這個賦值的行為,會觸發一些事情,當
a
原本不存在在obj
裡,但存在在obj
指到的prototype
中時,會觸發下列判斷prototype
中的a
,且a
的writable
為true
,則會再創建一個a
到obj
中。prototype
中的a
,且a
的writable
為false
,則不會有任何覆寫,且在嚴格模式時,會拋出錯誤。prototype
中的a
,且a
是個setter
,則不會像第一個一樣,被重複創建,而只是被呼叫而已。訪問到
prototype
中的a
,且a
的writable
為true
,則會再創建一個a
到obj
中訪問到
prototype
中的a
,且a
的writable
為false
,則不會有任何覆寫,且在嚴格模式時,會拋出錯誤訪問到
prototype
中的a
,且a
是個setter
,則不會像第一個一樣,被重複創建,而只是被呼叫而已The text was updated successfully, but these errors were encountered: