0

この質問の回答は、これを使用して関数が定義されているかどうかを確認することを示しています。

typeof yourFunction === 'function'

しかし、私はこれを非標準の関数link()で試しました。そして実際にはこれはfalseを返しました。この機能は、私が試したすべてのブラウザ(IE、Chrome、Opera、FireFox)で利用できます。

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

それからどこかで私は見つけます:

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

これは実際にはtrueを返します。違いは何ですか?最初のものが失敗する理由は何ですか?

4

2 に答える 2

3

Stringはコンストラクター関数であり、関数もオブジェクトです。プロパティを追加できます。

例えば:

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

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

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

これは、jQuery$がオブジェクト(例$.each())のように動作し、関数(例)のように動作するのと同じ理由$(selector)です。

など:

  • usingString.linkは、コンストラクター関数自体のプロパティにアクセスしています。これは存在しません。

  • usingは、すべての文字列に付属String.prototype.linkする関数にアクセスしlink()ます-存在する(そして使用する必要がある)

于 2012-05-10T01:26:57.230 に答える
0

文字列はオブジェクトであり、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
于 2012-05-10T01:28:14.767 に答える