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

查看:1502
本文介绍了javascript - 不明白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不需要定义的,系统的方法,不明白为什么会一直报这个错误。谢谢。

解决方案

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

这篇关于javascript - 不明白Uncaught TypeError: Cannot read property &#039;apply&#039; of undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆