var Car = function(model, owner){ this.model = model; this.owner = owner; this.pastOwners = []; } Car.prototype.honk = function(){ return this.model + " honked!"; } Car.prototype.sellCar = function(newOwner){ var oldOwner = this.owner; this.pastOwners.push(function(code){ if (code == 404){ return oldOwner; } else { return "Invalid Code!"; } }) this.owner = newOwner; } Car.prototype.sellCar = function(newOwner){ this.pastOwners.push( (function(pastOwner){ return function(code){ if (code == 404){ return pastOwner; } else { return "Invalid Code!"; }} })(this.owner) ) this.owner = newOwner; } // now let's create another class that inherits from Car var myCar = function(model, owner, color){ Car.apply(this, [model, owner]); // this line of code is interesting this.color = color; } // recall that ".apply" simply assigns the "this" of the function to whatever you specify // which means that when we define // var x = new Car("Honda", "Franklyn", "red"); // x is being assigned as "this" in Car. // so x.model = model, x.owner = owner, x.pastOwners = [] // we've assigned all the surface stuff, // but haven't assigned a prototype. // We have a new object for which we'eve defined model, owner and pastOwners, // but its prototype is currently still the generic {}. // There are now two ways to set the prototype of x to Car // 1. Using Object.create() // recall that Object.create(proto) returns an object whose prototype is "proto" myCar.prototype = Object.create(Car.prototype); // why we need OBject.create(Car.prototype) rather than Object.create(Car) because // Car is not the prototype. Car.prototype is the prototype. // 2. Using Object.setPrototypeOf() // Object.setPrototypeOf(myCar.prototype, Car.prototype); var x = new Car("Honda", "Franklyn", "red");
Примечания: прототипное наследование
schedule
02.11.2022