尝试从jQuery源重新创建.isFunction()

时间:2015-10-21 00:09:02

标签: javascript jquery function design-patterns

我试图通过打破一些碎片来从jQuery源学习一些东西。现在我要越过isFunction。在我的代码test中,而不是jQuery。问题是isFunction通过输出false stub来告诉我stub不是函数。

我注意到jquery并没有在我的代码中使用this中的return this.type(obj) === "function",而是在test.prototype ={中编写代码,jQuery将其写入jQuery.extend({也许这就是我的问题?我没有包括扩展功能。

尝试像jQuery的源代码结构一样保持答案我知道我的代码有点不同。

另外,你知道像jQuery这样的小型库可以用来学习吗?我现在不需要了解AJAX和承诺我只想学习代码结构和DOM操作。在jQuery中有很多信息。

var test = function(){

}
var class2type = {};
test.prototype ={
    type : function(obj){
        if(obj == null){
            return obj + "";
        }
        return typeof obj === "object" || typeof obj === "function" ?
                    class2type[ toString.call(obj) ] || "object" :
                    typeof obj;
    },
    isFunction :function(obj){
        return this.type(obj) === "function"
    }
}


var stub = function stub(){}
console.log(typeof stub)
console.log(test.prototype.isFunction(stub)) 

1 个答案:

答案 0 :(得分:0)

您错过了class2type的声明。基本上,发生了什么class2type[toString.call(obj)]正在返回undefined,因此test.prototype.type(stub)会返回"object",这不等于"function",所以{{ 1}}返回test.prototype.isFunction(stub)

要解决此问题,请将其添加到false

class2type