3.7 创建对象
JavaScript中的对象一部分是通过构造函数生成的,例如:
function Car(color, direction, mph) {
this.color = color || 'pink';
this.direction = direction || 0; // 0 = Straight ahead
this.mph = mph || 0;
this.gas = function gas(amount) {
amount = amount || 10;
this.mph += amount;
return this;
};
this.brake = function brake(amount) {
amount = amount || 10;
this.mph = ((this.mph - amount) < 0)? 0
: this.mph - amount;
return this;
};
}
var myCar = new Car();
test('Constructor', function () {
ok(myCar.color, 'Has a color');
equal(myCar.gas().mph, 10,
'.accelerate() should add 10mph.'
);
equal(myCar.brake(5).mph, 5,
'.brake(5) should subtract 5mph.'
);
});
使用私有变量来做数据封装:
function Car(color, direction, mph) {
var isParkingBrakeOn = false;
this.color = color || 'pink';
this.direction = direction || 0; // 0 = Straight ahead
this.mph = mph || 0;
this.gas = function gas(amount) {
amount = amount || 10;
this.mph += amount;
return this;
};
this.brake = function brake(amount) {
amount = amount || 10;
this.mph = ((this.mph - amount) < 0)? 0
: this.mph - amount;
return this;
};
this.toggleParkingBrake = function toggleParkingBrake() {
isParkingBrakeOn = !isParkingBreakOn;
return this;
};
this.isParked = function isParked() {
return isParkingBrakeOn;
}
}
var myCar = new Car();
test('Constructor with private property.', function () {
ok(myCar.color, 'Has a color');
equal(myCar.gas().mph, 10,
'.accelerate() should add 10mph.'
);
equal(myCar.brake(5).mph, 5,
'.brake(5) should subtract 5mph.'
);
ok(myCar.toggleParkingBrake().isParked(),
'.toggleParkingBrake works.'
);
});
对象字面量让对象构建的语法更为简单直观:
var myCar = {
color: 'pink',
direction: 0,
mph: 0,
gas: function gas(amount) {
amount = amount || 10;
this.mph += amount;
return this;
},
brake: function brake(amount) {
amount = amount || 10;
this.mph = ((this.mph - amount) < 0)? 0
: this.mph - amount;
return this;
}
};
test('Object literal notation.', function () {
ok(myCar.color, 'Has a color');
equal(myCar.gas().mph, 10,
'.accelerate() should add 10mph.'
);
equal(myCar.brake(5).mph, 5,
'.brake(5) should subtract 5mph.'
);
});
请注意,由于对象字面量不具备函数作用域,所以数据封装性会丢失。
时间: 2024-09-28 18:01:37