【问题标题】:Check for native defined functions with prototype使用原型检查本机定义的函数
【发布时间】:2012-05-10 01:23:16
【问题描述】:

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

【问题讨论】:

    标签: javascript function built-in


    【解决方案1】:

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

    • 使用String.prototype.link 访问每个字符串附带的link() 函数——它确实存在(你应该使用它)

    【讨论】:

    • 我想了想,this 确实有帮助,实际上typeof String().link === 'function' 返回了 true。这样,String 将创建一个空对象,并应检查链接“可用性”。
    • @Milo 但您创建一个对象只是为了检查link,而不是直接在原型中检查link
    • 哦,我没有那样想!这个比较实用。
    【解决方案2】:

    因为 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      相关资源
      最近更新 更多