Mar/080
Javascript Essentials
Looking into creating my own ASP.Net Control Extenders (like in the Ajax Control Toolkit), I found myself having to brush up on my Javascript. So here is a quick revision of what I (and maybe you too) need to remember.
Function declaration:
function SayHelloTo(nameStr) {
document.write('Hello ' + nameStr);
}
Function with return statement:
function add(x, y) {
return x + y;
}
Variable declaration within a function:
function add(x, y) {
var z = x+y;
return z;
}
Classes in Javascript:
function car(makeStr, modelStr, colourStr) {
this.make = makeStr;
this.model = modelStr;
this.colour = colourStr;
}
Note how the declaration of a class is exactly the same as declaring a function with the salient keyword being this in the declaration of the variables within the function.
To create an instance of an object:
car1 = new car('Toyota', 'Camry', 'Red');
To access a property within the object:
car1.make = 'Ford';
Class methods:
function drive()
{
with (this) document.write(make+' is going for a drive');
}
Once again, note the this keyword.
Declaring class methods as above is however expensive on memory as each car object has a corresponding drive object.
Functions and constants can instead be declared in what is called the prototype for a class:
car.prototype.drive = drive;
Constants may also be defined in the prototype:
car.prototype.topSpeed = 100;
A class prototype can also be declared all at once with the function bodies:
car.prototype =
{
drive : function()
{
document.write(this.make+' is going for a drive');
},stop : function()
{
document.write(this.make+' is stopping');
}
}
Happy Javascripting
No comments yet.
Leave a comment
No trackbacks yet.