1 Create an instance of an object using the constructor function
Constructors in JavaScript, like other object-oriented languages, cannot be called directly, and are invoked automatically when an object is created with the new keyword.
The following is a new example of using a constructor in JavaScript.
var myObject = new Object(); // 创建没有属性的通用对象。
var myBirthday = new Date(1961, 5, 10); // 创建一个 Date 对象。
var myCar = new Car(); // 创建一个用户定义的对象,并初始化其属性。
Writing constructors
You can use the new operator to combine predefined constructors such as Object (), Date (), and function () to create and initialize an object.
The powerful feature of object-oriented programming is the ability to define custom constructors to create custom objects that are used in scripts.
A custom constructor is created so that an object with the defined property can be created.
The following is an example of a custom function (note the use of this keyword).
function Circle (xPoint, yPoint, radius) {
this.x = xPoint; // 圆心的 x 坐标。
this.y = yPoint; // 圆心的 y 坐标。
this.r = radius; // 圆的半径。
}
When the Circle constructor is invoked, the value of the center point and the radius of the circle are given (all of these elements are necessary to fully define a unique circular object).
At the end of the Circle object contains three properties. Here's how to sample the Circle object.
var acircle = new Circle (5, 11, 99);
2 using prototypes to create objects
In JavaScript, you can use the prototype keyword to innovate member functions and properties for an object, and you can change the value of a prototype property in one object, and the new value will overwrite the default value, but only in that instance. Other objects belonging to this class are not affected by this change.
The following is an example of using a custom constructor, Circle (note the use of this keyword).
Circle.prototype.pi = Math.PI;
function ACirclesArea () {
return this.pi * this.r * this.r; // 计算圆面积的公式为 ?r2。
}
Circle.prototype.area = ACirclesArea; // 计算圆面积的函数现在是 Circle Prototype 对象的一个方法。
var a = ACircle.area(); // 此为如何在 Circle 对象上调用面积函数。
下面的示例是String对象中采用原型来定义的一个实例方法.
// 增加一个名为 trim 的函数作为
// String 构造函数的原型对象的一个方法。
String.prototype.trim = function()
{
// 用正则表达式将前后空格
// 用空字符串替代。
return this.replace(/(^\s*)|(\s*$)/g, "");
}
// 有空格的字符串
var s = " leading and trailing spaces ";
// 显示 " leading and trailing spaces (35)"
window.alert(s + " (" + s.length + ")");
// 删除前后空格
s = s.trim();
// 显示"leading and trailing spaces (27)"
window.alert(s + " (" + s.length + ")");
3 define static members of the class
Static members that define classes in JavaScript can be defined directly
For example, if I want to define a static method in a class to return an instance of a class.
You can first set a createnew to attach a method object to it:
Splitterbar.createnew = _createnew;
The following are examples of methods:
function _cretaenew()
{
var bar=new SplitterBar();
return bar;
}