Object-Oriented Programming with JavaScript, Part II: Methods

来源:百度文库 编辑:神马文学网 时间:2024/04/30 08:14:26
In this column we conclude our short series about Object-Oriented Programming (00P) with JavaScript. In Part I of this series, we covered the fundamentals. In this column, we focus more on encapsulation, especially on methods.
As we discussed in the first part of this series, JavaScript‘s support of object-oriented programming is quite impressive. Even though there are no formal classes or instances, there are objects, prototypes, and methods that mimic them. In fact, it is the methods that make the language so vibrant and powerful. You use methods to mimic class inheritance between objects. We‘ll show you how to define functions in JavaScript, and how to define methods with these functions. We‘ll show you where method definition does not match the rules for functions. We‘ll explain the exposure of private data elements, and how to protect them. In this column, we also cover contexts, scopes, and context switching. Understanding contexts and scopes will help you in writing as well as debugging complex scripts.
The examples in this column are for JavaScript 1.1 and above, for both Internet Explorer and Netscape, unless noted otherwise.
In this column, you will learn:
Constructing Objects
An object constructor is written as a regular function. Here is the Employee object:
function Employee() { this.dept = "HR"; this.manager = "John Johnson";}
When you create an object, it automatically inherits all Object‘s properties. The Object object is the base object for all native and user-defined objects. All objects inherit from this superclass. You can create an Object object as well:
var myObject = new Object();
The Object object has a dozen of properties and methods. Examples are constructor, toString(), and valueOf(). The object myObject above sports these properties.Alert the object. You should get [object Object]. You can pass a string to the Object constructor:
var myObject = new Object("foo");
Alert the object. You should get the string you passed to the constructor, "foo". The native objects sports the same properties, because they inherit from the Object class.Probe the constructor property of the Math object, Math.constructor. The answer you should get is that the Object object is the constructor of the Math object.