未访问的局部变量& '这'上下文执行

时间:2011-09-29 17:58:41

标签: javascript

我有以下一段代码让我无法工作[代码后的问题]

var LIB = function(){};

(function(){
var JSExpert = function(lname){
    if(!(this instanceof arguments.callee)){
        return new JSExpert(lname);
    }

    this.fname = "Later ";
    this.name = this.fname + lname;
};

JSExpert.prototype = {
    setFname: function(fname){
        this.fname = fname;
        return this; //for chaining
    },

    getName: function(){
        alert("javascript expert name is " + this.name);
    }
};

LIB.Expert = JSExpert;
return;

    window.JSExpert = JSExpert;
})();

现在来测试代码

LIB.Expert("Edwads").setFname("Dean").getName();

现在当你尝试代码时,setFname()方法应该在构造函数中由“Dean”改变“Later”而不是这样做,为什么呢????

第二个问题:我们在JSExpert中使用'this'。如何确定'this'的上下文后来不会被限制在'LIB'的上下文中并继续强制执行'JSExpert'并因此'LIB.Expert'?

由于

2 个答案:

答案 0 :(得分:0)

因为:

return;

window.JSExpert = JSExpert;

不正确,应该是:

window.JSExpert = JSExpert;

getName: function(){
    alert("javascript expert name is " + this.name);
}

应该是:

getName: function(){
    alert("javascript expert name is " + this.fname + this.lname);
}

lname需要是fname之类的属性。 Example


var LIB = function() {};

(function() {
    var JSExpert = function(lname) {
        if (!(this instanceof arguments.callee)) {
            return new JSExpert(lname);
        }
        this.lname = lname;
        this.fname = "Later ";
        this.name = this.fname + lname;
    };

    JSExpert.prototype = {
        setFname: function(fname) {
            this.fname = fname;
            return this; //for chaining
        },

        getName: function() {
            alert("javascript expert name is " + this.fname + ' ' + this.name);
        }
    };

    LIB.Expert = JSExpert;

    //window.JSExpert = JSExpert;
})();

LIB.Expert("Edwads").setFname("Dean").getName();

答案 1 :(得分:0)

1)改变

setFname: function(fname){
    this.fname = fname;
    return this; //for chaining
},

setFname: function(fname){
        this.name = this.name.slice(this.fname.length);
        this.name = fname + ' ' + this.name;
    this.fname = fname + ' ';
    return this; //for chaining
},

2)在构造函数中,检查this类型:

var JSExpert = function(lname){
    //If not an instance of this class creates a new object of this class and return it
    if(!(this instanceof arguments.callee)){
        return new JSExpert(lname);
    }

    this.fname = "Later ";
    this.name = this.fname + lname;
};

在其他功能中,您可以执行类似if (!(this instanceof JSExpert)) throw new Error('');的操作,抛出错误是您可以在此处执行的最佳操作,这是使用原型时的缺点。