AJAX - The Complete Reference

(avery) #1

PART IV


Appendix A: JavaScript Quick Reference 561


Instance Properties
Once an instance of an object is created, setting properties is similar to a standard
assignment:

instance.property = value;

and they can be accessed using the standard dot (‘.’) operator. For example, after creating
a simple object, we might just add a new property to it:

var angus = new Dog("Angus Dunedin Powell");
angus.color = "black";

Basic OOP Using Prototype
Despite what some people think, JavaScript is an object-oriented programming language—
it just doesn’t use the magic word “class,” at least not in the current 1.x generation of the
language. As a prototypical-based OOP language, we can add to constructors on the fly. For
example, we can extend Dog to have a sit() method now:

Dog.prototype.sit = function () {alert("I am sitting");};

So our created objects now have this feature:

angus.sit()

You can use prototypes to create basic inheritance. For example:

function Scotty(name)
{
this.name = name;
this.shortLegs = true;
}
Scotty.prototype = new Dog();

var angus = new Scotty("angus");
angus.bark(); // alerts woof woof as inherited from Dog
alert(angus.shortLegs); // alerts true

Using this idea, we can add prototypes to built-in objects like Array and even overwrite
any methods or properties you desire.

The this Statement
The this statement refers to the “current” object, that is, the object inside of which this is
invoked. Its syntax is:

this.property

It is typically used inside of a function (for example, to access the function’s length
property) or inside of a constructor in order to access the new instance being created.

function Dog(name)
{
alert(this); // shows reference to Object
this.name = name;
}
Free download pdf