2012-05-10 23 views
0

的答案從這個question本地定義的函數說用這個來檢查,如果函數的定義:檢查與原型

typeof yourFunction === 'function' 

但我已經試過這對非標準功能link()。實際上這返回了錯誤。該功能可用於我嘗試過的每個瀏覽器 - IE,Chrome,Opera,FireFox。

typeof String.link === 'function' // false 
typeof String.link() === 'function' // Uncaught error ... 

然後我的地方找到:

typeof String.prototype.link === 'function' //true 

實際上返回true。有什麼區別,爲什麼第一個失敗?

回答

3

String是一個構造函數,函數也是對象。你可以附加屬性。

For example:

function foo(){ 
    alert('from foo'); 
} 

foo.bar = function(){ 
    alert('bar on foo'); 
} 

foo();  //from foo 
foo.bar(); //bar on foo 

這是由於相同的原因如何jQuery的$的作用就像一個對象(例如$.each())和像功能以及(例如$(selector))。

所以:

  • 使用String.link正在訪問的構造函數本身的屬性 - 它不存在。因爲字符串是對象,而沒有鏈接()方法,該方法確實存在(並且你應該使用)

+0

我想過這個問題,[這](http://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript)實際上幫助,實際上'typeof String()。link ==='function''返回true。這種方式字符串將創建一個空的對象和鏈接「可用性」應該檢查它。 – Bakudan

+0

@Milo,但是你會創建一個對象來檢查'link',而不是直接在原型中檢查'link'。 – Joseph

+0

哦,我沒那麼想!這更實用。 – Bakudan

0

-

  • 使用String.prototype.link訪問自帶每串的link()功能。只有字符串有這種方法。看:

    String//Defines the Object 
    String.prototype//Defines the methods and properties that will be bound to a var of the type String 
    'foo'//This is a string 
    'foo'.link//So it has the link method 
    String//This is an Objecy that defines the strings 
    String.link//So it doesn't have the link method 
    String.prototype//An object that stores the methods and properties of the vars of type String 
    String.prototype.link//So it has the link method