0

这个问题的答案说使用它来检查是否定义了函数:

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。有什么区别,为什么第一个失败?

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正在访问构造函数本身的属性——它不存在。

  • usingString.prototype.link访问link()每个字符串附带的函数-确实存在(并且您应该使用)

于 2012-05-10T01:26:57.230 回答
0

因为 string 是 Object 并且没有 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 回答