1

我一直在研究一个 javascript 库。这是代码:

(function (window) {
        var regex = {
            Id : /^[#]\w+$/,
            Class : /^[.]\w+$/,     
            Tag : /^\w+$/,
            validSelector : /^([#]\w+|[.]\w+|\w+)$/
        },  
        tex = function(selector){
            //only some of the functions need to select an element
            //EX:
            // style: tex(selector).style(style);
            //one that would not need a selector is the random number function:
            // tex().random(from,to);
            if (selector){
                if (typeof selector === 'string'){
                    var valid = validSelector.test(selector);
                    if( valid ){
                        if(regex.Id.test(string)){ 
                            this = document.getElementById(selector);
                        }
                        if(regex.Class.test(string)){ 
                            this = document.getElementByClass(selector);
                        }
                        if(regex.Tag.test(string)){ 
                            this = document.getElementByTagName(selector);
                        }
                    }
                }else if(typeof selector === 'object'){
                    this = selector;
                }
                //this = document.querySelector(selector);
                // I could make a selector engine byt I only need basic css selectors.
            }
        },
        tex.prototype = {
            dit : function(){
                this.innerHTML = 'Hi?!?!?!'
            }
        };
        window.tex = tex;
})(window);

在我尝试在我的网页上使用该库之前,这一切看起来都是不错的代码。当我尝试激活它时,我收到一条错误消息,上面写着“错误:意外令牌'。'”指的是以下tex.prototype行:

},
tex.prototype = {
    dit : function(){

有谁知道我的代码有什么问题?

太感谢了!

4

3 回答 3

1

也许你应该在声明 'tex' 之后编写这个原型?

    },
    tex.prototype = {
        dit : function(){
            this.innerHTML = 'Hi?!?!?!'
        }
    };

改成:

};
tex.prototype = {
    dit : function(){
        this.innerHTML = 'Hi?!?!?!'
    }
};
于 2013-10-11T11:52:42.237 回答
0
var o = {};  // right
var o.a = 1; // wrong
o.a = 1;     // right

替换逗号:

};
tex.prototype = {
    dit : function(){

可能还有另一个问题this = ...;

this = 1; // ReferenceError: Invalid left-hand side in assignment

这意味着您不允许设置this关键字。

于 2013-10-11T11:49:12.277 回答
0

作为对我们之前讨论的回复,这里有一个快速修订:

var o;    // defines a new variable named "o"
o = {};   // sets the variable "o" as an empty object
o[0] = 1; // adds a property named "0" to this object

因此,此代码将一个新属性添加到this

this[0] = elem;

虽然这个崩溃:

this = elem; // ReferenceError: Invalid left-hand side in assignment
于 2013-10-11T12:16:23.197 回答