2015-10-20 26 views
-2

我正在閱讀關於js中的調用函數。 現在我有這樣的代碼JavaScript中的調用函數給出錯誤

var o = { 
 
    name: 'i am object', 
 
    age: 22 
 
} 
 

 
function saymyName(arguentToFunc) { 
 
    console.log('my name is ' + this.name + 'and thw argument passed is ' + arguentToFunc); 
 
} 
 

 
saymyName.apply(o, 'hello there');

但它給出了一個錯誤信息說Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type

在這本書是寫在明確的指南,第二個參數是傳遞給價值功能。例如這裏它是hello there 那麼爲什麼錯誤呢?

嘿根據書 。 apply needs this 如果一個函數被定義爲接受任意數量的參數,意味着什麼?我的意思是arbrital?

+0

嘿爲什麼我downvoted? –

+0

@耶,但我很困惑! –

回答

3

apply需要參數數組,你應該使用它作爲

saymyName.apply(o, ['hello there']); 

,否則你可以使用call

saymyName.call(o, 'hello there'); 
3

使用call而不是apply,因爲適用需要第二個參數是類似數組的對象。

使用申請當需要發送作爲參數傳遞給被調用的函數的值的陣列(例如通過使用參數對象的當前正在執行的功能的所有參數)。

Demo

var o = { 
 
    name: 'i am object', 
 
    age: 22 
 
}; 
 

 
function saymyName(arguentToFunc) { 
 

 
    console.log('my name is ' + this.name + 'and thw argument passed is ' + arguentToFunc); 
 
} 
 

 
saymyName.call(o, 'hello there');

另外,請參閱bind如何設置函數的爲一個固定值,不管它怎麼叫。

+0

如果一個函數被定義爲接受任意數量的參數,是什麼意思?我的意思是arbrital? –

+0

@MarcAndreJiacarrini我們是否真的需要告訴你[如何在字典中查找單詞](https://en.wiktionary.org/wiki/arbitrary)? – poke

+0

@poke字典包含許多含義的傢伙...哪一個適合這裏...先生酷傢伙? –