以下为构造函数方法创建类:
复制代码 代码如下:
function className (prop_1, prop_2, prop_3) {
this.prop1 = prop_1;
this.prop2 = prop_2;
this.prop3 = prop_3;}
复制代码 代码如下:
var obj_1 = new className(v1, v2, v3)
var obj_2 = new className(v1, v2, v3)
复制代码 代码如下:
function className (prop_1, prop_2, prop_3) {
this.prop1 = prop_1;
this.prop2 = prop_2;
this.prop3 = prop_3;
this.func = function new_meth (property) {
//coding here
}
}
在JavaScript里,对象的属性默认都是全局的,也就是说,对象内外都可以直接访问该属性。上面例子里this.prop1, this.prop2, this.prop3都是全局属性。
如何定义私有属性呢?使用var,下面的例子里,price就变成了私有属性!
复制代码 代码如下:
function Car( listedPrice, color ) {
var price = listedPrice;
this.color = color;
this.honk = function() {
console.log("BEEP BEEP!!");
};
}
复制代码 代码如下:
this.getPrice = function() {
//return price here!
return price;
--------------------------------------------------------------------------------
使用以下语法继承:
复制代码 代码如下:
ElectricCar.prototype = new Car();
复制代码 代码如下:
myElectricCar instanceof Car
复制代码 代码如下:
// 使用构造函数定义一个新的对象
function ElectricCar( listedPrice ) {
this.electricity=100;
var price = listedPrice;
}
// 使新对象继承Car
ElectricCar.prototype = new Car();
// 为新对象添加方法
ElectricCar.prototype.refuel = function(numHours) {
this.electricity =+ 5*numHours;
};
复制代码 代码如下:
function Car( listedPrice ) {
var price = listedPrice;
this.speed = 0;
this.numWheels = 4;
this.getPrice = function() {
return price;
};
}
Car.prototype.accelerate = function() {
this.speed += 10;
};
function ElectricCar( listedPrice ) {
var price = listedPrice;
this.electricity = 100;
}
ElectricCar.prototype = new Car();
// 重写accelerate方法
ElectricCar.prototype.accelerate = function() {
this.speed += 20;
};
// 添加新方法decelerateElectricCar.prototype.decelerate = function(secondsStepped) {
this.speed -= 5*secondsStepped;
};
myElectricCar = new ElectricCar(500);
myElectricCar.accelerate();
console.log("myElectricCar has speed " + myElectricCar.speed);
myElectricCar.decelerate(3);
console.log("myElectricCar has speed " + myElectricCar.speed);
新闻热点
疑难解答
图片精选