prototype
对象有点难以理解;然而这篇关于 OOP JavaScript 的文章可以帮助阐明一些观点。
简而言之,该prototype
对象为“接收者”对象提供了蓝图——您所要做的就是将接收者的prototype
属性指向您的蓝图对象。请注意,您可以拥有任意数量的原型蓝图对象接收者(因此 Car 和 Train 都可以指向一个公共 Vehicle 原型对象)。
您可以在原型对象中自由定义属性和函数,任何接收对象都可以使用它们,例如:
var vehiclePrototype = {
// A property which will be supplied to the recipient
cost: 0,
// A method which will be supplied the recipient
move: function () {
// Your prototype can refer to 'this' still.
console.log("Moving " + this.name);
};
}
您现在可以创建一个Car
使用vechiclePrototype
:
// Factory method for creating new car instances.
function createCar(name) {
// Define the Car's constructor function
function Car(name) {
this.name = name;
}
// Point the car's prototype at the vechiclePrototype object
Car.prototype = vechiclePrototype;
// Return a new Car instance
return new Car(name);
}
// Create a car instance and make use of the Prototype's methods and properties
var mustang = createCar(mustang);
mustang.cost = 5000;
mustang.move();
可以用类似的方式创建一个新的 Train 对象:
function createTrain(whilstleSound) {
// Define the Train's constructor function
function Train(name) {
this.whilstleSound = whilstleSound;
}
// Point the train's prototype at the vechiclePrototype object
Train.prototype = vechiclePrototype;
// Return a new Train instance
return new Train(name);
}
var ic125 = new Train("pooop pooop");
ic125.move();
使用原型继承的一大优点是两者的所有实例都Car
共享Train
完全相同的move
函数(而不是创建同一函数的多个实例),如果这些对象有很多实例,这会导致显着的内存节省。