Problem with classes in javascript
I wrote the following class in javascript
function main()
{
this.area ;
this.$= function(target)
{
if(target == undefined)
{
this.area = document;
}
else
{
this.area = document.getElementById(target);
if( this.area == null )
{
this.area = document.getElementsByTagName(target);
if( this.area[0] == null )
alert("Error value "+target+" passed to $() is no an id or name");//code to create variable
}
}
}
this.display = function(value)
{
if(this.area == undefined)
alert("Error in display() method...target not selectedddd");
开发者_StackOverflow社区else area.innerHTML = value;
}
}
and i always get the error message I given as alert. Why area is always null?
If I refer to area without using the this
keyword will it work. Is there any way to nest classes in javascript like
function()
{
this.a;
function()
{
}
}
The reason why it does not work is that this
refers to the inner function scope, not the outer function scope you call a "class".
Try something like this instead:
function MyClass() {
// This is the constructor.
}
MyClass.prototype = {
method: function() {
},
foo: function() {
}
};
var instance = new MyClasss();
instance.method();
I tried the class, and I don't get the error message.
Usage:
var m = new main();
m.$('x');
m.display('Replaced');
Demo: http://jsfiddle.net/ksNSG/
There is an error in the display
method, however. You are using area
instead of this.area
, but that doesn't cause the error message to be displayed, it just keeps the method from setting the content of the element.
Edit:
Regarding your comment to the question; the $
method doesn't return the object, so you can't chain it after the constructor like var m = new main().$('x');
, you have to call the $
method after creating the object.
You would have to add a return this;
last in the $
method in order to chain the calls that way.
精彩评论