引入一个js文件报错TypeError: Cannot set property 'extend' of undefined

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<script src="./aid.js"></script>
<script>
    function abc(){
        console.log('我是小abc')
    }

    var object1 = {
        apple: 0,
        banana: { weight: 52, price: 100 },
        cherry: 97
    };
    var object2 = {
        banana: { price: 200 },
        durian: 100
    };

    var object = Aid.extend({}, object1, object2);
</script>



</body>
</html>
var Aid = function() {
    var isFunctionCharacter = function(obj)
    {
        try {
            if(typeof obj === "function") { //是函数    其中 FunName 为函数名称
                console.log("is function");
            } else { //不是函数
                console.log("not is function");

            }
        } catch(e) {}
    }
    return { isFunction : isFunctionCharacter };
}();

Aid.fn = Aid.prototype

Aid.extend = Aid.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[0] || {}, // 默认第0个参数为目标参数
        i = 1,    // i表示从第几个参数凯斯想目标参数进行合并,默认从第1个参数开始向第0个参数进行合并
        length = arguments.length,
        deep = false;  // 默认为浅度拷贝

    // 判断第0个参数的类型,若第0个参数是boolean类型,则获取其为true还是false
    // 同时将第1个参数作为目标参数,i从当前目标参数的下一个
    // 处理深度拷贝情况
    if (typeof target === 'boolean') {
        deep = target;

        // Skip the boolean and the target
        target = arguments[i] || {};
        i++;
    }


    // 判断目标参数的类型,若目标参数既不是object类型,也不是function类型,则为目标参数重新赋值
    if (typeof target !== 'object' && !Aid.isFunction(target)) {
        target = {};
    }
}
阅读 3.7k
3 个回答

Aid.fn.extend 报错,Aid.fn = Aid.prototype,但是Aid不是函数呀,Aid.prototype是undefined。再Aid.fn = Aid.prototype的后面console.log(Aid)看一下

Aid 是一个object, 返回 { isFunction : isFunctionCharacter }, 他又不是一个构造函数, 你怎么在他的原型里添加方法?

Aid是模仿jquery做的一个方法吧? 那么

var Aid = function() {
    var isFunctionCharacter = function(obj)
    {
        try {
            if(typeof obj === "function") { //是函数    其中 FunName 为函数名称
                console.log("is function");
            } else { //不是函数
                console.log("not is function");

            }
        } catch(e) {}
    }
    return { isFunction : isFunctionCharacter };
}
// ();

这里的立即执行应该去掉吧, 这样应该可以

你可能需要换一种写法,让函数声明提升

(function Aid() {
    var isFunctionCharacter = function(obj)
    {
        try {
            if(typeof obj === "function") { //是函数    其中 FunName 为函数名称
                console.log("is function");
            } else { //不是函数
                console.log("not is function");

            }
        } catch(e) {}
    }
    return { isFunction : isFunctionCharacter };
})();
推荐问题