在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/C++  HTML/ 請問這個 `getType` 是一個函數嗎

請問這個 `getType` 是一個函數嗎

學習Javascript的過程中,遇到了下面的問題:

我需要封裝一個判斷對象類型的函數 getType,得到的結果不合人意,如下:

const getType = Object.prototype.toString.call

// 判斷 target 的類型
getType(target)

// Uncaught TypeError: getType is not a function
回答
編輯回答
伴謊

const getType = target => Object.prototype.toString.call(target);

2017年10月8日 02:12
編輯回答
吃藕丑

這是一個很特殊的問題,居然真有人遇到了

我們知道 Function 的原型鏈上有三個方法 .bind .call .apply。
事實上,你對這三個方法進行你給出代碼里的操作,都是會報錯的:

function f () {
}
const bind = f.bind
const call = f.call
const apply = f.apply

bind()    // TypeError: Bind must be called on a function
call()    // TypeError: call is not a function
apply()   // TypeError: apply is not a function

為什么會這樣?其實我們可以從 bind() 的錯誤信息中看出一點提示:.bind() .call() .apply() 這三個方法必須由一個函數為主體進行調用。
意思是說,這三個方法的使用,必須是 func.bind() func.call() func.apply() 這種形式,把它單獨賦值給一個變量去調用是不行的。
至于原因,仔細想想這三個方法的作用體會一下。

如果你需要封裝這樣一個 getType 的話,可以像樓上給出的方案那樣:

const getType = target => Object.prototype.toString.call(target)

希望對你有幫助

2017年8月22日 02:33