开发者

TypeError: Xjs("hi").getName is not a function showing in firebug console

开发者 https://www.devze.com 2023-03-17 06:46 出处:网络
Why is this开发者_StackOverflow code showing an error in Firebug? var Xjs =function(name){ if(!(this instanceof Xjs)) return new Xjs(name)

Why is this开发者_StackOverflow code showing an error in Firebug?

var Xjs =function(name){
    if(!(this instanceof Xjs)) return new Xjs(name)
};
Xjs.prototype={
    constructor:Xjs,
    Xjs:function(){this.name=name;},
    getName:function(){
        alert(this.name);
    }
}

In Firebug:

Xjs('hi').getName();


var Xjs =function(name){
    if(!(this instanceof Xjs)) return new Xjs(name)
    this.name = name;
};
Xjs.prototype={
    constructor:Xjs,
    getName:function(){
        alert(this.name);
    }
}
Xjs('hi').getName();

You do not need to pass to methods in the prototype the name treat this as an object. The name is already available as this.name to all members of that object


object fields must be members of the object itself not it's prototype try this:

var Xjs =function(name){
    if(!(this instanceof Xjs)) return new Xjs(name);
    this.name = name;        
};
Xjs.prototype={
    constructor:Xjs,   
    getName:function(){
        alert(this.name);
    }
}


Itay's solution is correct.

To explain: it's a bit hard to tell what your line

    Xjs:function(){this.name=name;},

is supposed to be accomplishing, especially since the variable name is not defined at that point.

But if I had to guess, I'd say that seem to be under the impression that adding an Xjs function to Xjs.prototype will act as a constructor (somehow), and perhaps magically get wired to the original Xjs function which accepts a name parameter.

This is, needless to say, false. All that adding Xjs : function () { this.name = name; } to Xjs.prototype means, is that you could do the following:

var instance = new Xjs("hi");
instance.Xjs();

In other words, it adds another method to Xjs instances, just like getName, although that method happens to be confusingly named Xjs.

(Of course, that code would immediately throw a ReferenceError since, as mentioned, name is not defined. But that's a separate issue.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号