Essentials of Javascript - Cultural View
Essentials of Javascript - Cultural View
Essentials of Javascript - Cultural View
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
JavaScript syntax 39<br />
Constructors<br />
Constructor functions simply assign values to slots <strong>of</strong> a newly created object. The values may be data or other<br />
functions.<br />
Example: Manipulating an object<br />
function MyObject(attributeA, attributeB) {<br />
}<br />
this.attributeA = attributeA;<br />
this.attributeB = attributeB;<br />
MyObject.staticC = "blue"; // On MyObject Function, not obj<br />
alert(MyObject.staticC); // blue<br />
obj = new MyObject('red', 1000);<br />
alert(obj.attributeA); // red<br />
alert(obj["attributeB"]); // 1000<br />
alert(obj.staticC); // undefined<br />
obj.attributeC = new Date(); // add a new property<br />
delete obj.attributeB; // remove a property <strong>of</strong> obj<br />
alert(obj.attributeB); // undefined<br />
delete obj; // remove the whole Object (rarely used)<br />
alert(obj.attributeA); // throws an exception<br />
The constructor itself is stored in the special slot constructor. So<br />
x = new Foo()<br />
// Above is almost equivalent to<br />
y = {};<br />
y.constructor = Foo;<br />
y.constructor();<br />
// except<br />
x.constructor == y.constructor // true<br />
x instance<strong>of</strong> Foo // true<br />
y instance<strong>of</strong> Foo // false, surprisingly.<br />
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using<br />
C++/Java terminology) as shown below. (The function object also has a special prototype property, as discussed in<br />
the Inheritance section below.)<br />
Object deletion is rarely used as the scripting engine will garbage collect objects that are no longer being referenced.