不明白Uncaught TypeError: Cannot read property 'apply' of undefined

 //这是一个构造函数
    function Set() { //大写首字母,约定写法
        this.values = {};  //集合数据保存在对象的属性里
        this.n = 0; //集合中的值的个数
        this.add.apply(this, arguments);//把所有参数都添加进这个集合
    }

    //添加原型方法add
    Set.prototype.add = function () {
        for (var i = 0; i < arguments.length; i++) {
            var val = arguments[i];
            var str = Set._v2s(val);
            if (!this.values.hasOwnProperty(str)) {
                this.values[str] = val;
                this.n++;
            }
        }
        return this; //支持链式方法调用,因为返回的是一个实例
    };
     Set._v2s = function (val) {
            switch (val){
                case undefined:
                    return 'u';
                case null:
                    return 'n';
                case true:
                    return 't';
                case false:
                    return 'f';
                default: switch (typeof val){
                    case 'number':
                        return '#'+ val;
                    case 'string':
                        return '"' + val;
                    default:
                        return '@' + objectId(val);
                }
                function objectId(o) {
                    var prop = "|**objectid**|";
                    if(!o.hasOwnProperty(prop)){
                        o[prop] = Set._v2s.next++;
                    }
                    return o[prop];
                }
            }
        };
    var test = [1,2,3];
    Set(test);

一直报错:Uncaught TypeError: Cannot read property 'apply' of undefined

根据我的理解,apply不需要定义的,系统的方法,不明白为什么会一直报这个错误。谢谢。

阅读 19.5k
2 个回答

你写个构造器倒是实例化啊。。。。。。你不实例化这个this.add.apply(this, arguments);里面的this是准备指向谁?

new Set(test)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题