在经典的面向对象编程语言中,构造函数是一种用于初始化新创建的对象并为之被分配内存的特殊方法。在JavaScript中,
一切都是对象,因此我们对对象的构造函数非常感兴趣。
对象的创建
在Javascript中,常见的三种创建对象的方法如下:
var newObject = {};
// or
var newObject = Object.create( Object.prototype );
// or
var newObject = new Object();
其中,最后一个例子中的Object构造函数为一个特定的值(或者空值)创建了一个object封装。它将会创建一个空的object,
然后返回。
然后有四个可以给一个对象分配键和值的方法:
// 1. 点号语法
//设置属性
newObject.someKey = "Hello World";
//获取属性
var key = newObject.someKey;
// 2. 方括号语法
//设置属性
newObject["someKey"] = "Hello World";
//获取属性
var key = newObject["someKey"];
// 3. Object.defineProperty
//设置属性
Object.defineProperty( newObject, "someKey", {
value: "for more control of the property's behavior",
writable: true,
enumerable: true,
configurable: true
});
//如果上面阅读起来有点困难,可以使用下面的简短方法
var defineProp = function ( obj, key, value ){
config.value = value;
Object.defineProperty( obj, key, config );
};
//使用
var person = Object.create( null );
//为person空对象分配属性
defineProp( person, "car", "Delorean" );
defineProp( person, "dateOfBirth", "1981" );
defineProp( person, "hasBeard", false );
// 4. Object.defineProperties
// 设置属性
Object.defineProperties( newObject, {
"someKey": {
value: "Hello World",
writable: true
},
"anotherKey": {
value: "Foo bar",
writable: false
}
});
//使用
// Create a race car driver that inherits from the person object
var driver = Object.create( person );
正如我们前面看到的,JavaScript不支持类的概念,但它支持处理对象的特殊构造器函数。通过加前缀关键字new
调用构造函数,我们可以告诉JavaScript我们想要该函数的行为如同一个构造函数,通过它来实例化一个有成员的新对象。
在构造函数中,关键字this指向新创建的对象:
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
}
// Usage:
// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
// and then open our browser console to view the
// output of the toString() method being called on
// these objects
console.log( civic.toString() );
console.log( mondeo.toString() );
以上是一个构造函数模式的简单版本,却有一些问题。一个是继承困难,另一个是使用Car构造函数是,
函数tostring()在每一个对象中被重新定义。
解决方法:
构造函数加原型
在JavaScript中,函数有一个叫做原型的属性。当我们条用一个JavaScript构造函数创建对象时,构造函数的原型的
所有属性对这个新创建的对象可用。通过这种方式,可以创建多个car对象共同访问相同的原型。由此,我们可以将上面的原始例子
扩展:
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}
Car.prototype.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
console.log( civic.toString() );
console.log( mondeo.toString() );